表示 XML
在您的 API 规范中,您可以同时描述 XML 和 JSON 格式的数据,因为它们很容易互换。例如,以下声明 —
1components:2 schemas:3 book:4 type: object5 properties:6 id:7 type: integer8 title:9 type: string10 author:11 type: string— 在 JSON 和 XML 中表示如下
JSON
1{ "id": 0, "title": "string", "author": "string" }XML
1<book>2 <id>0</id>3 <title>string</title>4 <author>string</author>5</book>如您所见,在 XML 表示中,对象名称充当父元素,属性转换为子元素。OpenAPI 3 格式提供了一个特殊的 xml 对象,以帮助您微调 XML 数据的表示。您可以使用此对象将某些属性转换为特性而不是元素,更改元素名称,添加命名空间以及控制数组项的转换。
更改元素名称
默认情况下,XML 元素获取与 API 声明中的字段相同的名称。要更改默认行为,请在您的规范中添加 xml/name 字段
元素名称
规范
1components:2 schemas:3 book:4 type: object5 properties:6 id:7 type: integer8 title:9 type: string10 author:11 type: string12 xml:13 name: "xml-book"XML
1<xml-book>2 <id>0</id>3 <title>string</title>4 <author>string</author>5</xml-book>特性名称
规范
1components:2 schemas:3 book:4 type: object5 properties:6 id:7 type: integer8 title:9 type: string10 xml:11 name: "xml-title"12 author:13 type: stringXML
1<book>2 <id>0</id>3 <xml-title>string</xml-title>4 <author>string</author>5</book>对于数组,xml/name 属性仅在另一个属性 – xml/wrapped – 设置为 true 时才起作用。请参阅下文。
将属性转换为特性
如上所述,默认情况下,属性转换为父“对象”元素的子元素。要使某些属性在生成的 XML 数据中成为特性,请使用 xml/attribute
规范
1book:2 type: object3 properties:4 id:5 type: integer6 xml:7 attribute: true8 title:9 type: string10 author:11 type: stringXML
1<book id="0">2 <title>string</title>3 <author>string</author>4</book>这仅适用于属性。对对象使用 xml/attribute 是没有意义的。
前缀和命名空间
为了避免元素名称冲突,您可以为元素指定命名空间和前缀。命名空间值必须是绝对 URI
1xml:2 prefix: "smp"3 namespace: "http://example.com/schema"命名空间前缀将被 JSON 忽略
1{ "author": "Mark Twain" }以下示例演示了如何添加命名空间和前缀
规范
1book:2 type: object3 properties:4 id:5 type: integer6 title:7 type: string8 author:9 type: string10 xml:11 prefix: "smp"12 namespace: "http://example.com/schema"XML
1<smp:book xmlns:smp="http://example.com/schema">2 <id>0</id>3 <title>string</title>4 <author>string</author>5</smp:book>如果需要,您可以只指定 prefix(如果命名空间在某个父元素中定义,则此方法有效)。您还可以为属性指定前缀。
包装数组
数组被转换为同名元素序列
规范
1books:2 type: array3 items:4 type: string5 example:6 - "one"7 - "two"8 - "three"XML
1<books>one</books>2<books>two</books>3<books>three</books>如果需要,您可以通过使用 xml/wrapped 属性添加一个包装元素
规范
1books:2 type: array3 items:4 type: string5 xml:6 wrapped: true7 example:8 - "one"9 - "two"10 - "three"XML
1<books>2 <books>one</books>3 <books>two</books>4 <books>three</books>5</books>如您所见,默认情况下,包装元素与项元素具有相同的名称。使用 xml/name 为包装元素和数组项提供不同的名称(这将帮助您解决可能的命名问题)
规范
1books:2 type: array3 items:4 type: string5 xml:6 name: "item"7 xml:8 wrapped: true9 name: books-array10 example:11 - "one"12 - "two"13 - "three"XML
1<books-array>2 <item>one</item>3 <item>two</item>4 <item>three</item>5</books-array>请注意,包装元素(在我们的示例中是 books)的 xml.name 属性仅在 wrapped 为 true 时才生效。如果 wrapped 为 false,则包装元素的 xml.name 将被忽略。