2

Possible Duplicate:
XML Attributes vs Elements

I have been reading on the web about when to use attribute versus element. The closest that I came to was in w3schools: "There are no rules about when to use attributes or when to use elements. Attributes are handy in HTML. In XML my advice is to avoid them. Use elements instead." Since I'm writing xsd shall I stick to Elements even for simple types?

Community
  • 1
  • 1
Moeman
  • 81
  • 1
  • 3

2 Answers2

5

While this is not a hard rule, and more of style treatment, the W3Schools provides the following explanation:

Attributes often provide information that is not a part of the data.

In my experience, this is a good guideline to follow. When I build XML applications, I follow this guideline and use attributes strictly for metadata of an element, and sub-elements for data that the element manages. To do this I ask questions like "Is this data about the XML entity (metadata)? Or is this data managed by the XML entity (stored data)?" Generally this gives a good indication of when the information is an attribute, or a sub-element.

For example. If I have the following collection of data that I need to organize in XML:

CustomerNumber="001"
FirstName="John"
LastName="Joe"
ProcessedDate="July 30, 2011"

I would organize the data in XML as follows:

<Customer processedDate="July 30, 2011">
    <CustomerNumber>001</CustomerNumber>
    <FirstName>John</FirstName>
    <LastName>Joe</LastName>
</Customer>
Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
TERACytE
  • 7,553
  • 13
  • 75
  • 111
0

With documents, use elements for stuff that's intended for the human reader and attributes for stuff intended for processing software.

With data, use elements except for ID values.

But I only say that because you wanted a rule. You don't have to follow it.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164