2

Im starting to learn a bit of xml and xslt, and I read on w3c W3Schools that they recommend you use elements instead of attributes. Whats your practice and why would you not want attributes -

is there any point where you want them really?

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Gleiemeister 2000
  • 731
  • 4
  • 9
  • 23

2 Answers2

4

Attributes are specifications to the data contained by the element. For example: A title is an element, the title's language an attribute.

<title lang="en">A simple title</title>

Attributes should never need to be rendered. They should contain additional information on the data, not data itself.

Goldfrapper
  • 100
  • 5
  • shouldnt they be rendered? Whats the purpose then? As I see it, its a matter of structure in your xml, but Im unsure what to use. Lang="en" could just as well be a child to the title. – Gleiemeister 2000 Nov 17 '10 at 12:12
  • -1: have to disagree about attributes only being specifications of the data. That's too limiting a role for them. – John Saunders Nov 17 '10 at 19:22
  • I said: Specification **to** the data; More like **meta information**. An Attribute is "A word or phrase syntactically subordinate to another word or phrase that it modifies;". It is of a descriptive nature. – Goldfrapper Nov 17 '10 at 21:12
2

The primary technical restrictions on attributes:

  • Attribute names are unique within the scope of the element they decorate.

  • Attribute order is not significant; XML processors are not required to process an element's attributes in the physical order in which they appear in the document.

  • Attribute values must be text content. They cannot contain elements, comments, or processing instructions. They cannot contain CDATA. They cannot contain unescaped markup characters.

These restrictions pretty strictly govern what it is and is not appropriate to use attributes for. Using attributes to model a map or dictionary whose keys are XML names and whose values can sensibly be represented as strings: good. Using attributes to serialize data whose order of processing is important: bad. (I'm looking at you, XAML.) Storing serialized XML in an attribute value: possible, but usually indicates that you're doing something wrong.

The idea that elements are for data and attributes are for metadata is a throwback to the days when XML wasn't used as a general-purpose serialization format. It's broadly ignored, largely because, in a lot of cases, the ability to represent name/value pairs tersely is of more obvious benefit than separation between data and metadata.

Robert Rossney
  • 94,622
  • 24
  • 146
  • 218