Sunday 14 November 2010

What are the differences and uses between elements and attributes?

 What are the differences and uses between elements and attributes?

Both elements and attributes have been designed to have a Name and a Value.
Elements can be parents of other elements and/or attributes and can be repeated within the same level of an XML document.  They also usually have start and end tags.
An element would look like: <Customer>John Doe</Customer>

Attributes consist of a named pair attached to an element start-tag.  An example of how an attribute is: <Customer ID="1234">John Doe</Customer>.  Attribute values must be enclosed in single or double quotes.  Attribute names must be unique within a single element occurrence.

When to use Elements versus Attributes is a very  tricky question and more related to architectural considerations than technical details.

Nevertheless there are things only Elements can do...

Elements can occur more than once (repeating) within the same level, while attributes can only appear once within the same level, example:

It is okay to have:
    <Root>
        <Customer ID="1234">John Doe</Customer>
        <Customer ID="2345">Jane Doe</Customer>
    </Root>

But it would be invalid to have:
    <Root>
       <Customer ID="1234" ID="2345">
    </Root>

Elements can be defined to be in a certain order, while attributes can appear in any order. As you get more familiar with XML, the distinction between an element and an attribute becomes more slippery. Attributes cannot contain markup and are thus guaranteed to be atomic, whether this is either good or bad depends on your point of view. Elements are flexible and hierarchical and can have zero or more textual elements in them. Again, either good or bad depending on how you look at it.

No comments:

Post a Comment