XML 元素 vs 屬性
在XML中,并有沒有規(guī)定何時使用屬性,以及何時使用子元素。
使用元素 vs 屬性
數(shù)據(jù)可以存儲在子元素或?qū)傩浴?/p>
讓我們來看下這些實例:
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
在第一個例子中"sex"是一個屬性。在后面一個例子中,"sex"是一個子元素。但是兩者都提供了相同的信息。
沒有特別規(guī)定何時使用屬性,以及何時使用子元素。我的經(jīng)驗是在HTML重多使用屬性,但在XML中,使用子元素,會感覺更像數(shù)據(jù)信息。
我喜歡的方式
我喜歡在子元素中存儲數(shù)據(jù)
下面的三個XML文檔包含完全相同的信息:
本例中使用"date"屬性:
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
本例中使用"date"元素:
<date>12/11/2002</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
本例中使用了擴(kuò)展的"date" 元素: (這是我最喜歡的方式):
<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>
避免使用屬性?
你應(yīng)該避免使用屬性?
一些屬性具有以下問題:
屬性不能包含多個值(子元素可以)
屬性不容易擴(kuò)展(為以后需求的變化)
屬性無法描述結(jié)構(gòu)(子元素可以)
屬性更難以操縱程序代碼
屬性值是不容易測試,針對DTD
如果您使用屬性作為數(shù)據(jù)容器,最終的XML文檔將難以閱讀和維護(hù)。 嘗試使用 元素 來描述數(shù)據(jù)。 to describe data. 只有在提供的數(shù)據(jù)是不相關(guān)信息時我們才建議使用屬性。
不要這個樣子結(jié)束(這不是XML應(yīng)該使用的):
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>
一個屬性規(guī)則的例外
規(guī)則總是有另外的
關(guān)于屬性的規(guī)則我有一個例外情況。
有時我指定的 ID 應(yīng)用了元素。這些 ID 應(yīng)用可在HTML中的很多相同的情況下可作為 NAME 或者 ID 屬性來訪問 XML 元素。以下實例展示了這種方式:
<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是只是一個計數(shù)器,或一個唯一的標(biāo)識符,來識別不同的音符,而不是作為數(shù)據(jù)的一部分。
在這里我想說的是,元數(shù)據(jù)(關(guān)于數(shù)據(jù)的數(shù)據(jù))應(yīng)當(dāng)存儲為屬性,而數(shù)據(jù)本身應(yīng)當(dāng)存儲為元素。