Possible Duplicate:
Should I use Elements or Attributes in XML?
I'm writing a configuration file in XML and I am pretty much new to the whole XML craze.
I'm curious what the SO community thinks about how various values should be represented in XML, as I can see a couple of ways to do it.
For example, when should a value be an attribute and when should it be nested within tags?
<node1 message="Hello world" id="1" />
Versus
<node1>
<message>Hello world</message>
<id>1</id>
</node1>
Obviously this is an extremely simple example...but are there pro's and con's for doing certain types as an attribute versus child nodes? Or both or neither?
I usually treat the attributes as metadata, or data about, or qualifying, the data within the nodes.
e.g. in your above example, I'd perhaps put the message as a text node, and have an attribute id relating to it.
There's no right or wrong here, but I find the above heuristic useful. One scenario where you may want to store as much as possible in attributes is for SAX parsing, in which your element callback has a parameter of all the attributes. i.e. you get one callback for all attributes, rather than 'n' callbacks, one for each piece of data. However that's a pretty specialised reason for constructing your document that way, and I'd think carefully before doing that.
Specifying with elements is certainly more verbose and tiresome, on the other hand it is not possible to validate as fully with attributes.
If you have two properties, one of which must be specified, you can validate this if they are child elements within the schema, with attributes you can only say if the attribute is required or not.
From the W3Schools Attributes page:
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)
In this (slightly contrived) example the vehicle might have both wings and wheels or some combination, with attributes we can't enforce that at least one is defined, whereas with elements we could use a choice element with a minOccurs to ensure at least one of the elements is defined.
The name attribute is always required so it can be either an attribute or element with no validation issues.
<vehicle name="plane" wheels="3" wings="2"/>
<vehicle name="sled" runners="2"/>
<vehicle name="robin reliant" wheels="3"/>
<vehicle name="plane">
<wheels>3</wheels>
<wings>2</wings>
</vehicle>
<vehicle name="sled">
<runners>2</runners>
</vehicle>
<vehicle name="robin reliant">
<wheels>3</wheels>
</vehicle>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With