XML 元素 vs. 屬性
在XML中,並沒有規定何時使用屬性,以及何時使用子元素。
使用元素 vs. 屬性
數據可以存儲在子元素或屬性。
讓我們來看下這些實例:
<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
在第一個例子中"sex"是一個屬性。在後面一個例子中,"sex"是一個子元素。但是兩者都提供了相同的資訊。
沒有特別規定何時使用屬性,以及何時使用子元素。我的經驗是在 HTML 中多使用屬性,但在XML中,使用子元素,會感覺更像數據資訊。
我喜歡的方式
我喜歡在子元素中存儲數據
下麵的三個XML文檔包含完全相同的資訊:
本例中使用"date"屬性:
<note date="12/11/2002">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
本例中使用"date"元素:
<note>
<date>12/11/2002</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<date>12/11/2002</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>2002</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<date>
<day>12</day>
<month>11</month>
<year>2002</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
避免使用屬性?
你應該避免使用屬性?
一些屬性具有以下問題:
- 屬性不能包含多個值(子元素可以)
- 屬性不容易擴展(為以後需求的變化)
- 屬性無法描述結構(子元素可以)
- 屬性更難以操縱程式代碼
- 屬性值是不容易測試,針對DTD
如果您使用屬性作為數據容器,最終的XML文檔將難以閱讀和維護。 嘗試使用元素來描述數據。只有在提供的數據是不相關資訊時我們才建議使用屬性。
不要這個樣子結束(這不是XML應該使用的):
<note day="12" month="11" year="2002"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>
一個屬性規則的例外
規則總是有另外的
關於屬性的規則我有一個例外情況。
有時我指定的 ID 應用了元素。這些 ID 應用可在HTML中的很多相同的情況下可作為 NAME 或者 ID 屬性來訪問 XML 元素。以下實例展示了這種方式:
<messages>
<note id="p501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="p502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not!</body>
</note>
</messages>
<note id="p501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="p502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not!</body>
</note>
</messages>
以上實例的XML檔中,ID是只是一個計數器,或一個唯一的識別字,來識別不同的音符,而不是作為數據的一部分。
在這裏我想說的是,元數據(關於數據的數據)應當存儲為屬性,而數據本身應當存儲為元素。