和 HTML 一樣,XML 元素在開始標記處可以帶屬性。屬性通常承載關於該元素的額外資訊。
你應該還記得這樣的 HTML 寫法:<IMG SRC="computer.gif">。其中 src 是 img 元素的屬性,提供了關於這個元素的額外資訊。
無論在 HTML 還是 XML 中,元素的屬性都在做同一件事:補充說明。
<img src="computer.gif"> <a href="demo.asp">
屬性值必須用引號包起來,單引號與雙引號都可以。以性別為例:
<person sex="female"> <person sex='female'>
這兩種寫法在一般情況下沒有差別,實務上雙引號更常見。但有些特殊情況必須用單引號,例如值本身含有雙引號時:
<gangster name='George "Shotgun" Ziegler'>
同一份資訊,兩種放法都成立:
<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="12/11/99"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> <!-- 寫法二:使用 date 元素 --> <note> <date>12/11/99</date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> <!-- 寫法三:把 date 再拆細(推薦) --> <note> <date> <day>12</day> <month>11</month> <year>99</year> </date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
用屬性存資料會衍生幾個問題:
如果把資料都塞進屬性,寫出來的 XML 會變得難讀也難操作。原則是:盡量用元素描述資料,只把與資料本身關係不大的額外資訊放進屬性。
像下面這樣就是反例:
<note day="12" month="11" year="99" to="Tove" from="Jani" heading="Reminder" body="Don't forget me this weekend!"></note>
規則總有例外。我對屬性的建議也有一個例外場景:有些時候應該為元素設計一個 ID 引用,讓你能透過它存取特定元素,就像 HTML 中的 name 與 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 屬性就像一個計數器或唯一標識符,用來在文件中區分不同的便條,它本身並不屬於便條的內容。
一句話總結:後設資料(描述資料的資料)適合用屬性存放,資料本身則應以元素形式呈現。