XML Attributes vs. Elements
For quite some time the XML community has been debating when to use attributes instead of elements. Some advocate a general rule of thumb to make everything an attribute unless its use requires the characteristics of an element. Others suggest using attributes only for metadata (data about data in the element). Many XML documents don’t use attributes at all.
Consequently the examples provided in this user manual attempt to demonstrate a variety of approaches. For example, the two XML documents below have exactly the same information but are composed differently:
No attributes used:
<PostAdr residential="true"> <name title="Mr."> <first>Sample</first> <last>Resident</last> </name> <street>123 Center Rd</street> <cty>Mankato</cty> <state>MN</state> <zip>56001</zip> <phone>123-123-1234</phone> <phone>321-321-4321</phone> </PostAdr>
Extensive attributes used:
<PostAdr residential="true" title="Mr." firstName="Sample" lastName="Resident" street="123 Center Rd" cty="Mankato" state="MN" zip="56001"> <phone>123-123-1234</phone> <phone>321-321-4321</phone> </PostAdr>
Because the <phone> data could potentially repeat many times, it could not be put into <PostAdr> as an attribute.
The following are some rules of thumb to apply during your schema development:
- Make a piece of data an element instead of an attribute if a piece of data needs to repeat itself multiple times within the same parent tag. Attributes can only be used once in each tag.
- Use an element when passing information the XML parser should not touch. The <![CDATA[don’t parse me]]> tag cannot be used in attributes, only in elements.
- Do not transmit a piece of data as an attribute if it could change in the future. For example, your XML might not need a phone extension now, but it could later. Attributes are less extensible than elements.
- Use elements if the data value could exceed 256 characters in length. No industry standards dictate this rule. Instead many consider it an acceptable maximum for attributes given the network infrastructure used for web services. To put this into perspective, some web servers limit the amount of data that can be passed on an HTTP GET command to 1024 bytes. Additionally, some parsers impose limits on the size of attributes they can handle.
Some people/sites advise avoiding the use of attributes because they don’t “look” as nice as elements. That is a poor reason for design consideration for something that will never be viewed by the end user. A solution would be to get an XML viewer that allows you to view the XML document in a fashion that suites your needs. On the other hand, beware of choosing an attribute over an element because you can’t foresee a need to subdivide or extend the data. Experienced business application programmers know that data requirements often change unpredictably.