XML: Attributes
Posted in XML on June 16th, 2009 by Chris H. – Be the first to commentDigging In
This is a continuation of my earlier article, XML: An Introduction, and is meant to go into XML a bit deeper than the previous article. Please read that article first if you have not yet done so, or this article may not make much sense.
Attributes
Taking a cue from the last article we’ll start with some sample HTML which will help explain things a bit better:
<html> <head> <title>My Sample Page</title> </head> <body> <img src="helloworld.jpg" height="50" width="200"> </body> </html>
In the preceding example the ‘img’ tag has three attributes (src, height, and width). Well XML is not any different. It supports attributes as well.
Starting with the code from the last example from the previous article:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <vehicles> <vehicle> <make>Ford</make> <model>Mustang</model> <year>2009</year> <price>$33,049.99</price> </vehicle> <vehicle> <make>Chevy</make> <model>Camaro</model> <year>1968</year> <price>$75,000</price> </vehicle> <vehicle> <make>Dodge</make> <model>Charger</model> <year>2007</year> <price>$26,743</price> </vehicle> <vehicle> <make>Pontiac</make> <model>Solstice</model> <year>2008</year> <price>$18,999.98</price> </vehicle> </vehicles> |
Lets say that we wanted to condense this code. We have a list of 5,000 cars, and listing them like this will get quite lengthy. We want something more concise and easier to read or scan.
We can modify our XML (using attributes of course) to get a more concise listing:
1 2 3 4 5 6 | <vehicles> <vehicle make="Ford" model="Mustang" year="2009" price="$33,049.99" /> <vehicle make="Chevy" model="Camaro" year="1968" price="$75,000" /> <vehicle make="Dodge" model="Charger" year="2007" price="$26,743" /> <vehicle make="Pontiac" model="Solstice" year="2008" price="$18,999.98" /> </vehicles> |
The code has gotten a lot shorter (and easier to read) as you can see. Going from 26 lines to just 6.
That concludes this article, but I will be following up shortly with a few posts on using XSL to process our newly written XML.