XML document design; When to use attributes vs. elements

Posted by ryan
at 1:39 PM on Thursday, March 04, 2004

My development team is in the process of designing some XML documents for use as a local file persistence format. The question has come up of when to use attributes vs. when to use elements.

I am of the following opinion:

  • Use attributes to represent singular, primitive data. For instance, the id of a user, the name of a user, the dob of a user would all be attributes because they are, well, attributes of the user.
  • Use child-elements to represent collections of items or complex types. For instance, the address of a user or the dept. of a user would be represented as a child element.

For example, a user XML element should be structured as

<user id="1" firstName="Ryan" lastName="Daigle">
    <address street="xxx My Street" city="My City" />
</user>

And not:

<user>
    <id>1</id>
    <firstName>Ryan</firstName>
    <lastName>Daigle</lastName>
    <address>
        <street>xxx My Street</street>
        <city>My City</city>
    </address>
</user>

Upon looking at this, it seems a bit extreme. Would anybody contest these document structures or have their own set of guidelines for when to use attributes vs. elements?

Comments

Leave a response