Should I use Elements or Attributes in XML? [duplicate]
Asked Answered
C

13

98

I am learning about XML Attributes from W3Schools.

The author mentions the following (emphasis mine):

XML Elements vs. Attributes

<person sex="female">
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>

<person>
  <sex>female</sex>
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>

In the first example sex is an attribute. In the last, sex is an element. Both examples provide the same information.

There are no rules about when to use attributes and when to use elements. Attributes are handy in HTML. In XML my advice is to avoid them. Use elements instead.

Avoid XML Attributes?

Some of the problems with using attributes are:

  • attributes cannot contain multiple values (elements can)
  • attributes cannot contain tree structures (elements can)
  • attributes are not easily expandable (for future changes)

Attributes are difficult to read and maintain. Use elements for data. Use attributes for information that is not relevant to the data.

So is the view of the author a famous one, or is this the best practice in XML?

Should Attributes in XML be avoided?

W3Schools also mentioned the following (emphasis mine):

XML Attributes for Metadata

Sometimes ID references are assigned to elements. These IDs can be used to identify XML elements in much the same way as the ID attribute in HTML. This example demonstrates this:

<messages>
  <note id="501">
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
  </note>
  <note id="502">
    <to>Jani</to>
    <from>Tove</from>
    <heading>Re: Reminder</heading>
    <body>I will not</body>
  </note>
</messages>

The ID above is just an identifier, to identify the different notes. It is not a part of the note itself.

What I'm trying to say here is that metadata (data about data) should be stored as attributes, and that data itself should be stored as elements.

Cotter answered 8/7, 2009 at 8:26 Comment(0)
S
75

Usage of attributes or elements is usually decided by the data you are trying to model.

For instance, if a certain entity is PART of the data, then it is advisable to make it an element. For example the name of the employee is an essential part of the employee data.

Now if you want to convey METADATA about data (something that provides additional information about the data) but is not really part of the data, then it is better to make it an attribute. For instance, lets say each employee has a GUID needed for back end processing, then making it an attribute is better.(GUID is not something that conveys really useful information to someone looking at the xml, but might be necessary for other purposes)

There is no rule as such that says something should be an attribute or a element.

Its not necessary to AVOID attributes at all costs..Sometimes they are easier to model, than elements. It really depends on the data you are trying to represent.

Sparhawk answered 8/7, 2009 at 8:33 Comment(1)
Attributes are not just for metadata - they're used for any kind of data that isn't hierarchical. See William Walseth's answer.Alkyne
L
50

My 0.02 five years after the OP is the exact opposite. Let me explain.

  1. Use elements when you're grouping similar data, and attributes of that data.
  2. Don't use elements for everything.
  3. If the data repeats (1 to many), it's probably an element
  4. If the data never repeats, and only makes sense when correlated to something else, it's an attribute.
  5. If data doesn't have other attributes (i.e. a name), then it's an attribute
  6. Group like elements together to support collection parsing (i.e. /xml/character)
  7. Re-use similar element names to support parsing data
  8. Never, ever, use numbers in element names to show position. (i.e. character1, character2) This practice makes it very hard to parse (see #6, parsing code must /character1, /character2, etc. not simply /character.

Considered another way:

  • Start by thinking of all your data as an attribute.
  • Logically group attributes into elements. If you know your data, you'll rarely need to convert attribute to an element. You probably already know when an element (collection, or repeated data) is necessary
  • Group elements together logically
  • When you run into the case the you need to expand, add new elements / attributes based on the logical structure an process above. Adding a new collection of child elements won't "break" your design, and will be easier to read over time.

For example, looking at a simple collection of books and major characters, the title won't ever have "children", it's a simple element. Every character has a name and age.

    <book title='Hitchhiker&apos;s Guide to the Galaxy' author='Douglas Adams'>
        <character name='Zaphod Beeblebrox' age='100'/>
        <character name='Arthur Dent' age='42'/>
        <character name='Ford Prefect' age='182'/>
    </book>

    <book title='On the Road' author='Jack Kerouac'>
        <character name='Dean Moriarty' age='30'/>
        <character name='Old Bull Lee' age='42'/>
        <character name='Sal Paradise' age='42'/>
    </book>

You could argue that a book could have multiple authors. OK, just expand by adding new author elements (optionally remove the original @author). Sure, you've broken the original structure, but in practice it's pretty rare, and easy to work around. Any consumer of your original XML that assumed a single author will have to change anyway (they are likely changing their DB to move author from a column in the 'book' table to an 'author' table).

<book title='Hitchhiker&apos;s Guide to the Galaxy'>
    <author name='Douglas Adams'/>
    <author name='Some Other Guy'/>
    <character name='Zaphod Beeblebrox' age='100'/>
    <character name='Arthur Dent' age='42'>
    <character name='Ford Prefect' age='182'/>
</book>
Leandraleandre answered 10/9, 2014 at 11:32 Comment(1)
2 other classics to avoid. 1) NEVER name an element name <attribute>. 2) Avoid the following. <attribute name='Name' value='Douglas Adams'/>, use <author name='Douglas Adams'/>. Sheesh.Leandraleandre
H
32

Not least important is that putting things in attributes makes for less verbose XML.

Compare

<person name="John" age="23" sex="m"/>

Against

<person>
    <name>
        John
    </name>
    <age>
        <years>
            23
        </years>
    </age>
    <sex>
        m
    </sex>
</person>

Yes, that was a little biased and exaggerated, but you get the point

Hom answered 8/7, 2009 at 11:55 Comment(6)
but doesnt using attributes also make it more complex, if not verbose.Cotter
@Ibn Saeed, I don't think it's more complex. It's as easy to grab an attribute from XML or an element.Brady
I agree, especially with very large documents, all that whitespace makes them really hard to read.Leandraleandre
What if you need to include John's five children and their ages?Everyone
@Everyone then you create a child element for each child under the single <person> element. The two are not exclusive. If you think of an element as a 'object' and attributes as 'data points' in that object, then its easy to decide when to use each.Quijano
Perhaps off-topic, but if you were using the superior SGML then using elements is actually less verbose because you can make the end tags optional!Persson
F
20

I've used Google to search for the exact question. First I landed on this article, Principles of XML design - When to use elements versus attributes. Though, it felt too long for a simple question as such. Anyhow, I've read through all the answers on this topic and didn't find a satisfactory summary. As such, I went back to the latter article. Here is a summary:

When do I use elements and when do I use attributes for presenting bits of information?

  • If the information in question could be itself marked up with elements, put it in an element.
  • If the information is suitable for attribute form, but could end up as multiple attributes of the same name on the same element, use child elements instead.
  • If the information is required to be in a standard DTD-like attribute type such as ID, IDREF, or ENTITY, use an attribute.
  • If the information should not be normalized for white space, use elements. (XML processors normalize attributes in ways that can change the raw text of the attribute value.)

Principle of core content

If you consider the information in question to be part of the essential material that is being expressed or communicated in the XML, put it in an element. If you consider the information to be peripheral or incidental to the main communication, or purely intended to help applications process the main communication, use attributes.

Principle of structured information

If the information is expressed in a structured form, especially if the structure may be extensible, use elements. If the information is expressed as an atomic token, use attributes.

Principle of readability

If the information is intended to be read and understood by a person, use elements. If the information is most readily understood and digested by a machine, use attributes.

Principle of element/attribute binding

Use an element if you need its value to be modified by another attribute. [..] it is almost always a terrible idea to have one attribute modify another.

This is a short summary of the important bits from the article. If you wish to see examples and full description of every case, then refer to the original article.

Finesse answered 27/4, 2013 at 15:37 Comment(2)
Following the information provided in the link has saved me a lot of headaches. Yes it produces more verbose XML but it is worth it. Follow these principles and it is hard to go wrong.Everyone
The link to "Principles of XML design - When to use elements versus attributes" by Uche Ogbuji didn't work for me. However, I could access the document via: web.archive.org/web/20170307092058/https://www.ibm.com/…Seaborne
S
7

Attributes model mapping. A set of attributes on an element isomorphizes directly onto a name/value map in which the values are text or any serializable value type. In C#, for instance, any Dictionary<string, string> object can be represented as an XML attribute list, and vice versa.

This is emphatically not the case with elements. While you can always transform a name/value map into a set of elements, the reverse is not the case, e.g.:

<map>
   <key1>value</key1>
   <key1>another value</key1>
   <key2>a third value</key2>
</map>

If you transform this into a map, you'll lose two things: the multiple values associated with key1, and the fact that key1 appears before key2.

The significance of this becomes a lot clearer if you look at DOM code that's used to update information in a format like this. For instance, it's trivial to write this:

foreach (string key in map.Keys)
{
   mapElement.SetAttribute(key, map[key]);
}

That code is concise and unambiguous. Contrast it with, say:

foreach (string key in map.Keys)
{
   keyElement = mapElement.SelectSingleNode(key);
   if (keyElement == null)
   {
      keyElement = mapElement.OwnerDocument.CreateElement(key);
      mapElement.AppendChild(keyElement);
   }
   keyElement.InnerText = value;
}
Sindhi answered 8/7, 2009 at 17:1 Comment(0)
I
4

You can't put a CDATA in an attribute. In my experience, sooner or later you are going to want to put single quotes, double quotes and/or entire XML documents into a "member", and if it's an attribute you're going to be cursing at the person who used attributes instead of elements.

Note: my experience with XML mainly involved cleaning up other peoples'. These people seemed to follow the old adage "XML is like violence. If using it hasn't solved your problem, then you haven't used enough."

Isobel answered 9/7, 2009 at 2:36 Comment(1)
If you're building with DOM, the putting single,double quotes isn't a problem in attributes. If you're building XML as a string, then you're open to this an tons of other problems.Leandraleandre
A
3

It all depends on what XML is used for. When it's mostly interop between software and machines - such as Web services it's easier to go all-elements if only for the sake of consistency (and also some frameworks prefer it that way, e.g. WCF). If it is targeted for human consumption - i.e. primarily created and/or read by people - then judicious use of attributes can improve readability quite a lot; XHTML is a reasonable example of that, and also XSLT and XML Schema.

Aged answered 8/7, 2009 at 8:33 Comment(0)
H
3

This is an example where attributes are data about data.

Databases are named by their ID attribute.

The "type" attribute of the database denotes what is expected to be found inside the database tag.

  <databases>

      <database id='human_resources' type='mysql'>
        <host>localhost</host>
        <user>usrhr</user>
        <pass>jobby</pass>
        <name>consol_hr</name>
      </database>

      <database id='products' type='my_bespoke'>
        <filename>/home/anthony/products.adb</filename>
      </database>

  </databases>
Hessney answered 1/4, 2014 at 15:47 Comment(0)
P
2

The author's points are correct (except that attributes may contain a list of values). The question is whether or not you care about his points.

It's up to you.

Platoon answered 8/7, 2009 at 8:29 Comment(1)
I would be using XML with PHP and MySQL. Mainly, on grounds of creating Charts or passing the data to a desktop application for manipulation.Cotter
A
2

I usually work on the basis that attributes are metadata - that is, data about the data. One thing I do avoid is putting lists in attributes. e.g.

attribute="1 2 3 7 20"

Otherwise you have an extra level of parsing to extract each element. If XML provides the structure and tools for lists, then why impose another yourself.

One scenario where you may want to code in preference for attributes is for processing speed via a SAX parser. Using a SAX parser you will get an element call back containing the element name and the list of attributes. If you had used multiple elements instead then you'll get multiple callbacks (one for each element). How much of a burden/timesink this is is up for debate of course, but perhaps worth considering.

Antihalation answered 8/7, 2009 at 8:33 Comment(2)
The standard way to do lists in attributes is attribute="1 2 3 7 20", which is supported by XML Schema.Platoon
i.e. whitespace separated ? I didn't know that. Now, can I extract those using (say) XPath and other standard toolings ?Antihalation
A
0

You could probably see the issue in a semantic way.

If the data is more tight linked with the element it would be an attribute.

i.e: an ID of an element, i would put it as an attribute of the element.

But it's true that while parsing a document attributes could cause more headaches than elements.

All depends on you, and how you design your Schema.

Auricular answered 8/7, 2009 at 8:35 Comment(0)
P
0

It's because of that kind of rubbish that you should avoid w3schools. If anything, that's even worse than the appalling stuff they have about JavaScript.

As a general rule, I would suggest that content - that is, data which are expected to be consumed by an end user (whether that be a human reading, or a machine receiving information for processing) - is best contained within an element. Metadata - for example an ID associated with a piece of content but only of value for internal use rather than for display to the end user - should be in an attribute.

Proser answered 8/7, 2009 at 11:45 Comment(0)
R
0

Here's another thing to keep in mind when deciding on an XML format: If I recall correctly, the values of "id" attributes must not be all numeric, they must meet the rules for names in XML. And of course the values must be unique. I have a project that must process files that don't meet these requirements (although they are clean XML in other respects), which made processing the files more convoluted.

Rossuck answered 9/7, 2009 at 2:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.