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
  • 160,644
  • 26
  • 247
  • 397
Álvaro García
  • 18,114
  • 30
  • 102
  • 193

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
  • 10,351
  • 10
  • 53
  • 85
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
  • 23,085
  • 46
  • 152
  • 242