?
本文檔使用 php中文網(wǎng)手冊(cè) 發(fā)布
XML元素具有屬性,類似 HTML。
屬性(Attribute)提供有關(guān)元素的額外信息。
在 HTML 中,屬性提供有關(guān)元素的額外信息:
<img src="computer.gif"> <a href="demo.html">
屬性通常提供不屬于數(shù)據(jù)組成部分的信息。在下面的實(shí)例中,文件類型與數(shù)據(jù)無(wú)關(guān),但是對(duì)需要處理這個(gè)元素的軟件來(lái)說(shuō)卻很重要:
<file type="gif">computer.gif</file>
屬性值必須被引號(hào)包圍,不過(guò)單引號(hào)和雙引號(hào)均可使用。比如一個(gè)人的性別,person 元素可以這樣寫:
<person sex="female">
或者這樣也可以:
<person sex='female'>
如果屬性值本身包含雙引號(hào),您可以使用單引號(hào),就像這個(gè)實(shí)例:
<gangster name='George "Shotgun" Ziegler'>
或者您可以使用字符實(shí)體:
<gangster name="George "Shotgun" Ziegler">
請(qǐng)看這些實(shí)例:
<person sex="female"> <firstname>Anna</firstname> <lastname>Smith</lastname> </person>
<person> <sex>female</sex> <firstname>Anna</firstname> <lastname>Smith</lastname> </person>
在第一個(gè)實(shí)例中,sex 是一個(gè)屬性。在第二個(gè)實(shí)例中,sex 是一個(gè)元素。這兩個(gè)實(shí)例都提供相同的信息。
沒有什么規(guī)矩可以告訴我們什么時(shí)候該使用屬性,而什么時(shí)候該使用元素。我的經(jīng)驗(yàn)是在 HTML 中,屬性用起來(lái)很便利,但是在 XML 中,您應(yīng)該盡量避免使用屬性。如果信息感覺起來(lái)很像數(shù)據(jù),那么請(qǐng)使用元素吧。
下面的三個(gè) XML 文檔包含完全相同的信息:
第一個(gè)實(shí)例中使用了 date 屬性:
<note date="10/01/2008"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
第二個(gè)實(shí)例中使用了 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>
第三個(gè)實(shí)例中使用了擴(kuò)展的 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>
因使用屬性而引起的一些問(wèn)題:
屬性不能包含多個(gè)值(元素可以)
屬性不能包含樹結(jié)構(gòu)(元素可以)
屬性不容易擴(kuò)展(為未來(lái)的變化)
屬性難以閱讀和維護(hù)。請(qǐng)盡量使用元素來(lái)描述數(shù)據(jù)。而僅僅使用屬性來(lái)提供與數(shù)據(jù)無(wú)關(guān)的信息。
不要做這樣的蠢事(這不是 XML 應(yīng)該被使用的方式):
<note day="10" month="01" year="2008" to="Tove" from="Jani" heading="Reminder" body="Don't forget me this weekend!"> </note>
有時(shí)候會(huì)向元素分配 ID 引用。這些 ID 索引可用于標(biāo)識(shí) XML 元素,它起作用的方式與 HTML 中 id 屬性是一樣的。這個(gè)實(shí)例向我們演示了這種情況:
<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 屬性僅僅是一個(gè)標(biāo)識(shí)符,用于標(biāo)識(shí)不同的便簽。它并不是便簽數(shù)據(jù)的組成部分。
在此我們極力向您傳遞的理念是:元數(shù)據(jù)(有關(guān)數(shù)據(jù)的數(shù)據(jù))應(yīng)當(dāng)存儲(chǔ)為屬性,而數(shù)據(jù)本身應(yīng)當(dāng)存儲(chǔ)為元素。