XML属性

XML元素可以具有属性,就像HTML一样。 属性旨在包含与特定元素相关的数据。

XML属性必须加引号

属性值必须始终用引号引起来。可以使用单引号或双引号。 对于一个人的性别,<person>元素可以这样写:

<person gender="female">
<!--或者 -->
<person gender='female'>

如果属性值本身包含双引号,则可以使用单引号或实体引用。

<gangster name='George "Shotgun" Ziegler'>
<gangster name="George &quot;Shotgun&quot; 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文档包含完全相同的信息:

<!--在第一个示例中使用date属性:-->
<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!">
## 元数据的XML属性 有时,将ID引用分配给元素。这些ID可以用来标识XML元素,其方式与HTML中的id属性大致相同。此示例说明了这一点 ``` Tove Jani Reminder Don't forget me this weekend! Jani Tove Re: Reminder I will not ``` 上面的id属性用于标识不同的笔记。它不是笔记本身的一部分。 我在这里要说的是元数据(有关数据的数据)应存储为属性,而数据本身应存储为元素。
原文地址:https://www.cnblogs.com/laop520/p/13741204.html