views:

469

answers:

10

Hello

I am learning XML from W3schools.

Here: hXXp://www.w3schools.com/xml/xml_attributes.asp

The author mentions the following:
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 ?

Update: W3Schools also mentioned the following:
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.

+1  A: 

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.

John Saunders
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.
Ibn Saeed
+7  A: 

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.

Prashanth
That makes sense. Thanks :)
Ibn Saeed
+2  A: 

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.

Pavel Minaev
+1  A: 

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.

Brian Agnew
The standard way to do lists in attributes is attribute="1 2 3 7 20", which is supported by XML Schema.
John Saunders
i.e. whitespace separated ? I didn't know that. Now, can I extract those using (say) XPath and other standard toolings ?
Brian Agnew
A: 

Probably you could see the issue in a semantic way.

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

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 attributtes could cause more headaches than elements.

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

HyLian
A: 

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.

NickFitz
+2  A: 

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

flybywire
but doesnt using attributes also make it more complex, if not verbose.
Ibn Saeed
@Ibn Saeed, I don't think it's more complex. It's as easy to grab an attribute from XML or an element.
Nathan Koop
A: 

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;
}
Robert Rossney
A: 

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.

Grimarr
+1  A: 

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."

Coxy