跳到内容

表示 XML

在您的 API 规范中,您可以同时描述 XML 和 JSON 格式的数据,因为它们可以轻松互换。例如,以下声明 —

1
components:
2
schemas:
3
book:
4
type: object
5
properties:
6
id:
7
type: integer
8
title:
9
type: string
10
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 字段添加到您的规范中

元素名称

规范

1
components:
2
schemas:
3
book:
4
type: object
5
properties:
6
id:
7
type: integer
8
title:
9
type: string
10
author:
11
type: string
12
xml:
13
name: "xml-book"

XML

1
<xml-book>
2
<id>0</id>
3
<title>string</title>
4
<author>string</author>
5
</xml-book>

特性名称

规范

1
components:
2
schemas:
3
book:
4
type: object
5
properties:
6
id:
7
type: integer
8
title:
9
type: string
10
xml:
11
name: "xml-title"
12
author:
13
type: string

XML

1
<book>
2
<id>0</id>
3
<xml-title>string</xml-title>
4
<author>string</author>
5
</book>

对于数组,只有在另一个属性 – xml/wrapped – 设置为 true 时,xml/name 属性才起作用。请参见下文。

将属性转换为特性

如上所述,默认情况下,属性会转换为父“对象”元素的子元素。要使某些属性成为生成的 XML 数据中的特性,请使用 xml/attribute

规范

1
book:
2
type: object
3
properties:
4
id:
5
type: integer
6
xml:
7
attribute: true
8
title:
9
type: string
10
author:
11
type: string

XML

1
<book id="0">
2
<title>string</title>
3
<author>string</author>
4
</book>

这仅适用于属性。对对象使用 xml/attribute 是没有意义的。

前缀和命名空间

为避免元素名称冲突,您可以为元素指定命名空间和前缀。命名空间值必须是绝对 URI

1
xml:
2
prefix: "smp"
3
namespace: "http://example.com/schema"

命名空间前缀将被 JSON 忽略

1
{ "author": "Mark Twain" }

下面的示例显示了如何添加命名空间和前缀

规范

1
book:
2
type: object
3
properties:
4
id:
5
type: integer
6
title:
7
type: string
8
author:
9
type: string
10
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 (如果命名空间在某些父元素中定义,则此方法有效)。您还可以为特性指定前缀。

包装数组

数组被转换为相同名称的元素序列

规范

1
books:
2
type: array
3
items:
4
type: string
5
example:
6
- "one"
7
- "two"
8
- "three"

XML

1
<books>one</books>
2
<books>two</books>
3
<books>three</books>

如果需要,您可以使用 xml/wrapped 属性添加包装元素

规范

1
books:
2
type: array
3
items:
4
type: string
5
xml:
6
wrapped: true
7
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 为包装元素和数组项提供不同的名称(这将帮助您解决可能的命名问题)

规范

1
books:
2
type: array
3
items:
4
type: string
5
xml:
6
name: "item"
7
xml:
8
wrapped: true
9
name: books-array
10
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>

请注意,只有当 wrapped 为 *true* 时,包装元素(在我们的示例中为 books)的 xml.name 属性才起作用。如果 wrapped 为 *false*,则忽略包装元素的 xml.name

参考

XML 对象

没有找到您要找的内容? 咨询社区
发现错误? 请告诉我们