XML 元素:指的是從開始標簽到結(jié)束標簽的部分,元素可包含其他元素、文本或者兩者的混合物,并且元素也可以擁有屬性。
XML 屬性:提供關(guān)于元素的額外的信息。
在XML中,并有沒有規(guī)定何時使用屬性,以及何時使用子元素。
數(shù)據(jù)可以存儲在子元素或?qū)傩灾小?/p>
讓我們來看下這些實例:
<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中,使用子元素,會感覺更像數(shù)據(jù)信息。
我喜歡在子元素中存儲數(shù)據(jù)
下面的三個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>
本例中使用"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" 元素: (這是我最喜歡的方式):
<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>
你應該避免使用屬性?
一些屬性具有以下問題:
如果您使用屬性作為數(shù)據(jù)容器,最終的XML文檔將難以閱讀和維護。 嘗試使用 元素 來描述數(shù)據(jù)。 to describe data. 只有在提供的數(shù)據(jù)是不相關(guān)信息時我們才建議使用屬性。
不要這個樣子結(jié)束(這不是XML應該使用的):
<note day="12" month="11" year="2002"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>
規(guī)則總是有另外的
關(guān)于屬性的規(guī)則我有一個例外情況。
有時我指定的 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>
以上實例的XML文件中,ID是只是一個計數(shù)器,或一個唯一的標識符,來識別不同的音符,而不是作為數(shù)據(jù)的一部分。
在這里我想說的是,元數(shù)據(jù)(關(guān)于數(shù)據(jù)的數(shù)據(jù))應當存儲為屬性,而數(shù)據(jù)本身應當存儲為元素。
更多建議: