XML 元素可以在开始标签中包含属性,类似 HTML。
属性 (Attribute) 提供关于元素的额外信息。
XML 属性从 HTML,你会回忆起这个:<img src="http://www.rdxx.com/Files/Pic/2008-8/16/HJ1F6GK183J2C11C22.gif">。"src" 属性提供有关 <img> 元素的额外信息。
在 HTML 中(以及在 XML 中),属性提供有关元素的额外信息:
| <img src="http://www.rdxx.com/Files/Pic/2008-8/16/HJ1F6GK183J2C11C22.gif"> <a href="demo.asp"> |
属性通常提供不属于数据组成部分的信息。在下面的例子中,文件类型与数据无关,但是对需要处理这个元素的软件来说却很重要:
| <file type="gif">computer.gif</file> |
属性值必须被引号包围,不过单引号和双引号均可使用。比如一个人的性别,person 标签可以这样写:
| <person sex="female"> |
或者这样也可以:
| <person sex='female'> |
注释:如果属性值本身包含双引号,那么有必要使用单引号包围它,就像这个例子:
| <gangster name='George "Shotgun" Ziegler'> |
或者可以使用实体引用:
| <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> |
在第一个例子中,sex 是一个属性。在第二个例子中,sex 则是一个子元素。两个例子均可提供相同的信息。
没有什么规矩可以告诉我们什么时候该使用属性,而什么时候该使用子元素。我的经验是在 HTML 中,属性用起来很便利,但是在 XML 中,您应该尽量避免使用属性。如果信息感觉起来很像数据,那么请使用子元素吧。
我最喜欢的方式下面的三个 XML 文档包含完全相同的信息:
第一个例子中使用了 date 属性:
| <note date="08/08/2008"> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting this weekend!</body> </note> |
第二个例子中使用了 date 元素:
| <note> <date>08/08/2008</date> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting this weekend!</body> </note> |
第三个例子中使用了扩展的 date 元素(这是我的最爱):
| <note> <date> <day>08</day> <month>08</month> <year>2008</year> </date> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting this weekend!</body> </note> |
因使用属性而引起的一些问题:
- 属性无法包含多个值(子元素可以)
- 属性无法描述树结构(子元素可以)
- 属性不易扩展(为未来的变化)
- 属性难以阅读和维护
请尽量使用元素来描述数据。而仅仅使用属性来提供与数据无关的信息。
不要做这样的蠢事(这不是 XML 应该被使用的方式):
| <note day="08" month="08" year="2008" to="George" from="John" heading="Reminder" body="Don't forget the meeting this weekend!"> </note> |
有
上一页 下一页






