XML元素具有属性,类似 HTML。
属性(Attribute)提供有关元素的额外信息。
在 HTML 中,属性提供有关元素的额外信息:
<img src="computer.gif">
<a href="demo.html">属性值必须被引号包围,不过单引号和双引号均可使用。比如一个人的性别,person 元素可以这样写:
<person sex="female">如果属性值本身包含双引号,您可以使用单引号,就像这个实例:
<gangster name='George "Shotgun" Ziegler'>请看这些实例:
<person sex="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person> <person>
<sex>female</sex>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>下面的三个 XML 文档包含完全相同的信息:
第一个实例中使用了 date 属性:
<note date="10/01/2008">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>第三个实例中使用了扩展的 date 元素(这是我的最爱):
<note>
<date>
<day>10</day>
<month>01</month>
<year>2008</year>
</date>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>因使用属性而引起的一些问题:
属性难以阅读和维护。请尽量使用元素来描述数据。而仅仅使用属性来提供与数据无关的信息。
不要做这样的蠢事(这不是 XML 应该被使用的方式):
<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>