目录

XML 属性


XML 元素可以有属性,就像 HTML 一样。

属性旨在包含与特定元素相关的数据。


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>

在第一个示例中,性别是一个属性。在最后一个例子中,性别是一个元素。两个示例都提供相同的信息。

XML 中没有关于何时使用属性或何时使用元素的规则。



我最喜欢的方式

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

第一个示例中使用了日期属性:

<note date="2008-01-10">
  <to>Tove</to>
  <from>Jani</from>
</note>

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

<note>
  <date>2008-01-10</date>
  <to>Tove</to>
  <from>Jani</from>
</note>

第三个示例中使用了扩展的 <date> 元素:(这是我最喜欢的):

<note>
  <date>
    <year>2008</year>
    <month>01</month>
    <day>10</day>
  </date>
  <to>Tove</to>
  <from>Jani</from>
</note>

避免使用 XML 属性?

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

  • 属性不能包含多个值(元素可以)
  • 属性不能包含树结构(元素可以)
  • 属性不易扩展(以供将来更改)

不要以这样的方式结束:

<note day="10" month="01" year="2008"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>

元数据的 XML 属性

有时,ID 引用会分配给元素。这些 ID 可用于标识 XML 元素,其方式与 HTML 中的 id 属性非常相似。这个例子证明了这一点:

<messages>
  <note id="501">
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
  </note>
  <note id="502">
    <to>Jani</to>
    <from>Tove</from>
    <heading>Re: Reminder</heading>
    <body>I will not</body>
  </note>
</messages>

上面的 id 属性用于标识不同的注释。它不是注释本身的一部分。

我在这里想说的是,元数据(关于数据的数据)应该存储为属性,而数据本身应该存储为元素。