加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 23:27:46 所属栏目:百科 来源:网络整理
导读:感觉XML拿着就能用,但是就是不能用好。今天简单的学习了一下,终于知道什么时候使用原始什么时候使用属性了。 以下内容来自: http://www.w3school.com.cn/xml/xml_attributes.asp XML 元素 vs. 属性 请看这些例子: person sex="female" firstnameAnna/fir

感觉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 >
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note> 
date="08/08/2008"

第二个例子中使用了 date 元素:

<note>

<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note> 
<date>08/08/2008</date>

第三个例子中使用了扩展的 date 元素(这是我的最爱):

<note>

<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>
<date>
  <day>08</day>
  <month>08</month>
  <year>2008</year>
</date>

避免 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 >
    <to>George</to>
    <from>John</from>
    <heading>Reminder</heading>
    <body>Don't forget the meeting!</body>
  </note>
  <note >
    <to>John</to>
    <from>George</from>
    <heading>Re: Reminder</heading>
    <body>I will not</body>
  </note> 
</messages>
id="501"id="502"

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

在此我们极力向您传递的理念是:元数据(有关数据的数据)应当存储为属性,而数据本身应当存储为元素。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读