XML中元素VS属性
我想但凡使用XML的开发者特别是开发新手都或多或少有过这样的疑惑:到底什么信息应该写在属性里,什么信息 应该写在元素里呢?属性和元素到底有哪些区别呢?哪些信息更加适合放在属性(或元素)里呢?在这篇博客中,我们 将一起学习和区别XML开发中元素和属性的区别以及如何更好地使用XML的元素和属性。 一、关于定义
从上面的定义,我们可以看出,属性强调的是关于元素的“额外(附加)”信息,而,元素在XML中主要用来存储数据。所以,二者的区别在于属性侧重于附属信息,而属性通常提供不属于数据组成部分的信息。 二、实例分析
第一种:date为note的属性 <note date="08/08/2008">
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
第二种:date为单独的简单元素 <note>
<date>08/08/2008</date>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
第三种:date分解为复合元素 <note>
<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>
因使用属性而引起的一些问题:
假如现在有很多便条(note),我们需要编号以示每个便条的区别,这个时候,我们可以采用如下的方式: <messages>
<note 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>
分析:上面的 ID 仅仅是一个标识符,用于标识不同的便签。它并不是便签数据的组成部分。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |