您的位置:首页 > 其它

XML中何时使用元素何时使用属性

2013-09-03 22:12 393 查看
感觉XML拿着就能用,但是就是不能用好。今天简单的学习了一下,终于知道什么时候使用原始什么时候使用属性了。

以下内容来自:
http://www.w3school.com.cn/xml/xml_attributes.asp


XML 元素 vs. 属性

请看这些例子:
<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 [code]date="08/08/2008"
>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
[/code]

第二个例子中使用了 date 元素:
<note>
[code]<date>08/08/2008</date>

<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
[/code]

第三个例子中使用了扩展的 date 元素(这是我的最爱):
<note>
[code]<date>
<day>08</day>
<month>08</month>
<year>2008</year>
</date>

<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
[/code]


避免 XML 属性?

因使用属性而引起的一些问题:
属性无法包含多重的值(元素可以)
属性无法描述树结构(元素可以)
属性不易扩展(为未来的变化)
属性难以阅读和维护

请尽量使用元素来描述数据。而仅仅使用属性来提供与数据无关的信息。

不要做这样的蠢事(这不是 XML 应该被使用的方式):
<note day="08" month="08" year="2008"
to="George" from="John" heading="Reminder"
body="Don't forget the meeting!">
</note>



针对元数据的 XML 属性

有时候会向元素分配 ID 引用。这些 ID 索引可用于标识 XML 元素,它起作用的方式与 HTML 中 ID 属性是一样的。这个例子向我们演示了这种情况:
<messages>
<note [code]id="501"
>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
<note
id="502"
>
<to>John</to>
<from>George</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>
[/code]

上面的 ID 仅仅是一个标识符,用于标识不同的便签。它并不是便签数据的组成部分。

在此我们极力向您传递的理念是:元数据(有关数据的数据)应当存储为属性,而数据本身应当存储为元素。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  xml 元素 属性 元数据