跳至內容

表示 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>

請注意,只有在 wrappedtrue 時,包裝元素(在我們的範例中為 books)的 xml.name 屬性才有效。如果 wrappedfalse,則會忽略包裝元素的 xml.name

參考

XML 物件

找不到您要的內容嗎?詢問社群
發現錯誤?告訴我們