XML 属性

XML 元素可以在开始标签中包含属性,类似 HTML。

属性 (Attribute) 提供关于元素的额外(附加)信息。

XML 属性必须加引号

属性值必须被引号包围,不过单引号和双引号均可使用。

比如一个人的性别,<person> 标签可以这样写:

<person gender="female">

或者这样也可以:

<person gender='female'>

如果属性值本身包含双引号,则可以使用单引号,如下例所示:

<gangster name='George "Shotgun" Ziegler'>

或者您可以使用字符实体:

<gangster name="George "Shotgun" Ziegler">

XML 元素与属性

请看这两个例子:

<person gender="female">
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>

<person>
  <gender>female</gender>
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>

在第一个例子中,sex 是一个属性。在第二个例子中,sex 则是一个子元素。两个例子均可提供相同的信息。

XML 中没有规则可以告诉我们什么时候该使用属性,而什么时候该使用子元素。我的经验是在 HTML 中,属性用起来很便利,但是在 XML 中,您应该尽量避免使用属性。如果信息感觉起来很像数据,那么请使用子元素吧。

我最喜欢的方式

下面的三个 XML 文档包含完全相同的信息:

第一个例子中使用了 date 属性:

<note date="2008-01-10">
  <to>George</to>
  <from>John</from>
</note>

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

<note>
  <date>2008-01-10</date>
  <to>George</to>
  <from>John</from>
</note>

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

<note>
  <date>
    <year>2008</year>
    <month>01</month>
    <day>10</day>
  </date>
  <to>George</to>
  <from>John</from>
</note>

避免使用 XML 属性?

使用属性时需要考虑的一些事项是:

  • 属性不能包含多个值(元素可以)
  • 属性无法描述树结构(元素可以)
  • 属性不易扩展(为未来的变化)

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

不要做这样的蠢事(这不是 XML 应该被使用的方式):

<note day="10" month="01" year="2008"
to="George" from="John" heading="Reminder"
body="Don't forget the meeting!">
</note>

针对元数据的 XML 属性

有时候会向元素分配 ID 引用。这些 ID 索引可用于标识 XML 元素,它起作用的方式与 HTML 中 ID 属性是一样的。这个例子向我们演示了这种情况:

<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 仅仅是一个标识符,用于标识不同的便签。它并不是便签数据的组成部分。

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