Representating XML

In your API specification, you can describe data in both XML and JSON formats as they are easily interchangeable. For example, the following declaration

components:
  schemas:
    book:
      type: object
      properties:
        id:
          type: integer
        title:
          type: string
        author: 
          type: string

is represented in the following way in JSON and XML:

JSON

XML

As you can see, in XML representation, the object name serves as a parent element and properties are translated to child elements. The OpenAPI 3 format offers a special xml object to help you fine-tune representation of XML data. You can use this object to transform some properties to attributes rather than elements, to change element names, to add namespaces and to control transformations of array items.

Change Element Names

By default, XML elements get the same names that fields in the API declaration have. To change the default behavior, add the xml/name field to your spec:

Element name

Specification

XML

Attribute name

Specification

XML

For arrays, the xml/name property works only if another property – xml/wrapped – is set to true. See below.

Convert Property to an Attribute

As we said above, by default, properties are transformed to child elements of the parent “object” element. To make some property an attribute in the resulting XML data, use the xml/attribute:

Specification

XML

This works only for properties. Using xml/attribute for objects is meaningless.

Prefixes and Namespaces

To avoid element name conflicts, you can specify namespace and prefix for elements. The namespace value must be an absolute URI:

Namespace prefixes will be ignored for JSON:

The example below shows how you can add namespaces and prefixes:

Specification

XML

If needed, you can specify only prefix (This works in case the namespace is defined in some parent element). You can also specify prefixes for attributes.

Wrapping Arrays

Arrays are translated as a sequence of elements of the same name:

Specification

XML

If needed, you can add a wrapping element by using the xml/wrapped property:

Specification

XML

As you can see, by default, the wrapping element has the same name as item elements. Use xml/name to give different names to the wrapping element and array items (this will help you resolve possible naming issues):

Specification

XML

Note that the xml.name property of the wrapping element (books in our example) has effect only if wrapped is true. If wrapped is false, xml.name of the wrapping element is ignored.

Reference

XML Object

Last updated