Xml Attributes Vs Elements

A FAQ related to ExtensibleMarkupLanguage

Can someone try to explain the difference between these two forms and when one would use them:

Form1:

<TAGNAME VAL1="some value" VAL2="somevalue">
Body of text, and possibly nested tags.
</TAGNAME>

Form2:
<TAGNAME>
<VAL1>
some value
</VAL1>
<VAL2>
someothervalue
</VAL2>
Body of text, and possibly nested tags.
</TAGNAME>

In SGML land this is a FAQ. See http://www.oasis-open.org/cover/elementsAndAttrs.html for a full discussion. There are practical differences between the two forms - for instance, in Form2 above the leading whitespace in VAL1 can be interpreted by applications. In Form1, an attribute is used so the leading whitespace is always ignored.

General rule of thumb is that tags describe content and attributes should only define special formatting (searching the contents of tags is easier and more often implemented than searching attribute values).

This question is also answered by XmlPcdataVsAttribute


BTW, I'd not use form 2 at all. ;) In the 2nd case, the text should be put into a <TEXT> element.


Maybe...

<TAGNAME>
<VAL1>some value</VAL1>
<VAL2>someothervalue</VAL2>
Body of text, and possibly nested tags.
</TAGNAME>
or...
<TAGNAME>
<VAL1>some value</VAL1>
<VAL2>someothervalue</VAL2>
<TEXT>Body of text, and possibly nested tags.</TEXT>
</TAGNAME>
...if you're worried about leading and trailing spaces.

A word of caution - the first version above is an example of an XML construct, "mixed content", the handling of which can get very tricky in XML "schema languages". Mixed content (an element node which has child nodes of both types, character-data and element nodes) should be used sparingly.


EditText of this page (last edited January 16, 2001) or FindPage with title or text search