2

I have a doubt and it is when to use an attribute and when a child or grandchild.

For example, I can have an element with two attribute but I can have two this element with two children, one for each attribute.

So my question is when it is a good idea to use attributes and when to use children.

John Saunders
  • 159,224
  • 26
  • 237
  • 393
Álvaro García
  • 16,711
  • 26
  • 88
  • 167

2 Answers2

1

I would use childs when their elements are related, e. g. there is a "car" child with "Color" and "Manufacturer" Elements. On the other hand, when there is only one unrelated Element it could be an attribute. Most XML I have seen does favor childs over attributes - so I would use attributes sparingly.

Christian Sauer
  • 9,530
  • 9
  • 50
  • 76
1

I use an attribute when it only lives as data associated to it's element.

When the data can also live as a separate entity or it can have attributes/child of it's own or it's a collection, I create a child element

For example

  • the VIN of a car is an attribute
  • the color of a car can be a child,but 'red' is not really meaningful so it's an attribute
  • Wheels is a child because it's a collection
  • wheel is a child because it can have attributes
  • Person name is an attribute
  • Person's daughter is a child element (can have attributes, and childs)

That's how I approach it.

Michel
  • 22,509
  • 44
  • 145
  • 229