Using elements and attributes

2007-09-19 10:55:22 by Kjell-Åke Gafvelin

I had a discussion last week with one of the devs (Andreas Assermark) in the project regarding when to use attributes or elements in xml documents used for messaging. What came out of was that when expressing business data in the xml document it should be done using elements and attributes should be used to express meta data about the business data as what type of data it is, when it was updated, if it has been printed e.t.c.

Here is an example of how such an xml document could look like:

<Order xmlns:meta="" 
  Invoiced="true" Printed="false" Closed="false" meta:Created="2007-09-15 10:00:00">
    <Address Type="Customer">
      <Name>GeekProject Inc.</Name>
      <Street>100 Nerd Road</Street>
      <PostCode>123 55</PostCode>
    <Address Type="Delivery">
      <Name>GeekProject Warehouse</Name>
      <Street>15 Storage Street</Street>
      <PostCode>123 70</PostCode>

In this document I have put all business data into the elements where it is easy to get a quick overview of what is actually in the document. In the Address element I have an attribute named Type which allows me to add a specific delivery address if the order should not be delivered directly to the customer.

In the Order element there is three attribute named Invoiced, Printed and Closed. Using these attributes I can display the status of the order without interfering with the actual business data. I have also added a namespace named meta to the document to allow attibutes to be added that describe the state of the document from a system standpoint.

By using this format in a xml document you will get documents that are more stuctured and hav a more logical grouping of the information.