XML 屬性
XML 元素可以在開始標(biāo)簽中包含屬性,類似 HTML。
屬性 (Attribute) 提供關(guān)于元素的額外(附加)信息。
XML 屬性
從 HTML,你會回憶起這個:<img src="computer.gif">。"src" 屬性提供有關(guān) <img> 元素的額外信息。
在 HTML 中(以及在 XML 中),屬性提供有關(guān)元素的額外信息:
<img src="computer.gif"> <a href="demo.asp">
屬性通常提供不屬于數(shù)據(jù)組成部分的信息。在下面的例子中,文件類型與數(shù)據(jù)無關(guān),但是對需要處理這個元素的軟件來說卻很重要:
<file type="gif">computer.gif</file>
XML 屬性必須加引號
屬性值必須被引號包圍,不過單引號和雙引號均可使用。比如一個人的性別,person 標(biāo)簽可以這樣寫:
<person sex="female">
或者這樣也可以:
<person sex='female'>
注釋:如果屬性值本身包含雙引號,那么有必要使用單引號包圍它,就像這個例子:
<gangster name='George "Shotgun" Ziegler'>
或者可以使用實體引用:
<gangster name="George "Shotgun" 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 則是一個子元素。兩個例子均可提供相同的信息。
沒有什么規(guī)矩可以告訴我們什么時候該使用屬性,而什么時候該使用子元素。我的經(jīng)驗是在 HTML 中,屬性用起來很便利,但是在 XML 中,您應(yīng)該盡量避免使用屬性。如果信息感覺起來很像數(shù)據(jù),那么請使用子元素吧。
我最喜歡的方式
下面的三個 XML 文檔包含完全相同的信息:
第一個例子中使用了 date 屬性:
<note date="08/08/2008"
>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
第二個例子中使用了 date 元素:
<note>
<date>08/08/2008</date>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
第三個例子中使用了擴展的 date 元素(這是我的最愛):
<note>
<date>
<day>08</day>
<month>08</month>
<year>2008</year>
</date>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
避免 XML 屬性?
因使用屬性而引起的一些問題:
- 屬性無法包含多重的值(元素可以)
- 屬性無法描述樹結(jié)構(gòu)(元素可以)
- 屬性不易擴展(為未來的變化)
- 屬性難以閱讀和維護
請盡量使用元素來描述數(shù)據(jù)。而僅僅使用屬性來提供與數(shù)據(jù)無關(guān)的信息。
不要做這樣的蠢事(這不是 XML 應(yīng)該被使用的方式):
<note day="08" month="08" year="2008" to="George" from="John" heading="Reminder" body="Don't forget the meeting!"> </note>
針對元數(shù)據(jù)的 XML 屬性
有時候會向元素分配 ID 引用。這些 ID 索引可用于標(biāo)識 XML 元素,它起作用的方式與 HTML 中 ID 屬性是一樣的。這個例子向我們演示了這種情況:
<messages> <noteid="501"
> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note> <noteid="502"
> <to>John</to> <from>George</from> <heading>Re: Reminder</heading> <body>I will not</body> </note> </messages>
上面的 ID 僅僅是一個標(biāo)識符,用于標(biāo)識不同的便簽。它并不是便簽數(shù)據(jù)的組成部分。
在此我們極力向您傳遞的理念是:元數(shù)據(jù)(有關(guān)數(shù)據(jù)的數(shù)據(jù))應(yīng)當(dāng)存儲為屬性,而數(shù)據(jù)本身應(yīng)當(dāng)存儲為元素。