XML 屬性


XML元素具有屬性,類似 HTML。

屬性(Attribute)提供有關元素的額外資訊。


XML 屬性

在 HTML 中,屬性提供有關元素的額外資訊:

<img src="computer.gif">
<a href="demo.html">

屬性通常提供不屬於數據組成部分的資訊。在下面的實例中,檔類型與數據無關,但是對需要處理這個元素的軟體來說卻很重要:

<file type="gif">computer.gif</file>


XML 屬性必須加引號

屬性值必須被引號包圍,不過單引號和雙引號均可使用。比如一個人的性別,person 元素可以這樣寫:

<person sex="female">

或者這樣也可以:

<person sex='female'>

如果屬性值本身包含雙引號,您可以使用單引號,就像這個實例:

<gangster name='George "Shotgun" Ziegler'>

或者您可以使用字元實體:

<gangster name="George &quot;Shotgun&quot; Ziegler">


XML 元素 vs. 屬性

請看這些實例:

<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>

在第一個實例中,sex 是一個屬性。在第二個實例中,sex 是一個元素。這兩個實例都提供相同的資訊。

沒有什麼規矩可以告訴我們什麼時候該使用屬性,而什麼時候該使用元素。我的經驗是在 HTML 中,屬性用起來很便利,但是在 XML 中,您應該儘量避免使用屬性。如果資訊感覺起來很像數據,那麼請使用元素吧。


我最喜歡的方式

下麵的三個 XML 文檔包含完全相同的資訊:

第一個實例中使用了 date 屬性:

<note date="10/01/2008">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

第二個實例中使用了 date 元素:

<note>
<date>10/01/2008</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

第三個實例中使用了擴展的 date 元素(這是我的最愛):

<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>


避免 XML 屬性?

因使用屬性而引起的一些問題:

  • 屬性不能包含多個值(元素可以)
  • 屬性不能包含樹結構(元素可以)
  • 屬性不容易擴展(為未來的變化)

屬性難以閱讀和維護。請儘量使用元素來描述數據。而僅僅使用屬性來提供與數據無關的資訊。

不要做這樣的蠢事(這不是 XML 應該被使用的方式):

<note day="10" month="01" year="2008"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>


針對元數據的 XML 屬性

有時候會向元素分配 ID 引用。這些 ID 索引可用於標識 XML 元素,它起作用的方式與 HTML 中 id 屬性是一樣的。這個實例向我們演示了這種情況:

<messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>

上面的 id 屬性僅僅是一個識別字,用於標識不同的便簽。它並不是便簽數據的組成部分。

在此我們極力向您傳遞的理念是:元數據(有關數據的數據)應當存儲為屬性,而數據本身應當存儲為元素。