0

Possible Duplicate:
XML attribute vs XML element

I often tend to create xml out of my c# and php objects with their properties and their data to be able to store the data and structure in files, databases and to be able to port it to other systems.

My question is what the pros and cons are (if any) using an element structure or attribute structure.

Element structure

<Body>
  <Row Name="Gender">
    <Col>
      <Key>FieldId</Key>
      <Value>1</Value>
    </Col>
    <Col>
      <Key>ParentId</Key>
      <Value></Value>
    </Col>
  </Row>
  <Row Name="Weight">
    <Col>
      <Key>FieldId</Key>
      <Value>3</Value>
    </Col>
    <Col>
      <Key>ParentId</Key>
      <Value></Value>
    </Col>
  </Row>
</Body>

Attribute structure

<Body>
  <Row Name="Gender">
    <Col Key="FieldId" Value="1" />
    <Col Key="ParentId" Value="0" />
  </Row>
  <Row Name="Weight">
    <Col Key="FieldId" Value="2" />
    <Col Key="ParentId" Value="0" />
  </Row>
</Body>

Any recommendations and advices are welcome!

Community
  • 1
  • 1
Eric Herlitz
  • 25,354
  • 27
  • 113
  • 157

2 Answers2

1

I prefer 1st version, because:

Some of the problems with attributes are:

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

Metadata (data about data) should be stored as attributes, and that data itself should be stored as elements.

Reference: http://www.w3schools.com/DTD/dtd_el_vs_attr.asp

Community
  • 1
  • 1
Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
1

I generally prefer a hybrid style, where the "main content" for each element is the text node. In your example, "Value" is clearly the main content, so I would use:

<Body>
  <Row Name="Gender">
    <Col Key="FieldId">1</Col>
    <Col Key="ParentId">0</Col>
  </Row>
  <Row Name="Weight">
    <Col Key="FieldId">2</Col>
    <Col Key="ParentId">0</Col>
  </Row>
</Body>

My main argument for this style is that it combines legibility with support for a wide variety of content / values: Attribute style frequently chokes on line-breaks in content (eg MSXML and .Net will parse correctly but normalize the attribute content when you output the source Xml again), so if you want to preserve text formatting, an attribute-centric style is generally a bad choice.

In the comment-linked question XML attribute vs XML element, several people describe it as a "data vs meta-data" question, which I think sums it up nicely. Data in elements, meta-data in attributes.

Community
  • 1
  • 1
Tao
  • 13,457
  • 7
  • 65
  • 76