XML: attributes or children? [duplicate]
-
05-07-2019 - |
Question
This question already has an answer here:
- XML attribute vs XML element 20 answers
In XSD, SOAP and other XML conventions you'll often see things like:
<book>
<title>Harry Potter</title>
<author>J.K. Rowling</author>
</book>
Now I'm wondering, what happened to attributes? To me it makes more sense to write this as:
<book title="Harry Potter" author="J.K. Rowling" />
But apparently, for some reason, smarter people than me chose otherwise. Could someone explain why, and what attributes are for then?
Solution
Some people consider the difference a matter of personal preference. There are a few guidlines out there you can follow.
OTHER TIPS
There's no hard and fast rule. I tend to use attributes for metadata about the data contained in the elements. e.g
<book author="JK Rowling" published="September 2001">Harry Potter</book>
although usage/particular requirements will determine this more than anyrhing else.
Another issue is the subsequent processing. If you're using a SAX processor then this format will result in one method callback with the atteribute structure populated. Putting the data in multiple elements will result in the corresponding number of method calls (this may be an optimisation too far, but it may be worth considering depending on the quantity of data)