XML elements can have attributes, just like HTML.
Attributes provide additional information about an element.
XML Attributes
In HTML, attributes provide additional information about elements:<img src="computer.gif"> <a href="demo.asp"> |
<file type="gif">computer.gif</file> |
XML Attributes Must be Quoted
Attribute values must always be quoted. Either single or double quotes can be used. For a person's sex, the person element can be written like this:<person sex="female"> |
<person sex='female'> |
<gangster name='George "Shotgun" Ziegler'> |
<gangster name="George "Shotgun" Ziegler"> |
XML Elements vs. Attributes
Take a look at these examples:<person sex="female"> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> |
<person> <sex>female</sex> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> |
There are no rules about when to use attributes or when to use elements. Attributes are handy in HTML. In XML my advice is to avoid them. Use elements instead.
My Favorite Way
The following three XML documents contain exactly the same information:A date attribute is used in the first example:
<note date="10/01/2008"> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> |
<note> <date>10/01/2008</date> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> |
<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> |
Avoid XML Attributes?
Some of the problems with using attributes are:- attributes cannot contain multiple values (elements can)
- attributes cannot contain tree structures (elements can)
- attributes are not easily expandable (for future changes)
Don't end up like this:
<note day="10" month="01" year="2008" to="Tove" from="Jani" heading="Reminder" body="Don't forget me this weekend!"> </note> |
XML Attributes for Metadata
Sometimes ID references are assigned to elements. These IDs can be used to identify XML elements in much the same way as the id attribute in HTML. This example demonstrates this:<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> |
What I'm trying to say here is that metadata (data about data) should be stored as attributes, and the data itself should be stored as elements.
Comments
Post a Comment