XML 元素可以有属性,就像 HTML 一样。
属性旨在包含与特定元素相关的数据。
属性值必须始终加引号。可以使用单引号或双引号。
对于一个人的性别,<person>元素可以这样写:
<person gender="female">
或者像这样:
<person gender='female'>
如果属性值本身包含双引号,则可以使用单引号,如下例所示:
<gangster name='George "Shotgun" Ziegler'>
或者您可以使用字符实体:
<gangster name="George "Shotgun" Ziegler">
看看这两个例子:
<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>
使用属性时需要考虑的一些事项是:
不要以这样的方式结束:
<note day="10" month="01" year="2008"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>
有时,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 属性用于标识不同的注释。它不是注释本身的一部分。
我在这里想说的是,元数据(关于数据的数据)应该存储为属性,而数据本身应该存储为元素。
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!