About Me

Friday, 13 April 2012

XML Tree - Ancestor

Anyone that came before you in your family tree is your ancestor. This means your mom, dad, grandfather and great-great-great-grandmother are all your ancestors.


Although it may seem strange to some, XML has adopted this terminology to define relationships between various XML elements in the same "family". Element A is the ancestor of element B if the following is true:
  • Element B is contained within element A.

Determining Ancestry

If you are trying to eyeball if one element is an ancestor of another element, then you are going to need to find the opening and closing tags of both elements to determine the relationship.
We have highlighted pop and amount in our lemonade.xml document; you must determine which element is the ancestor.

XML Code, lemonade.xml:

<inventory>
 <drink>
  <lemonade>
   <price>$2.50</price>
   <amount>20</amount>
  </lemonade>
  <pop>
   <price>$1.50</price>
   <amount>10</amount>
  </pop>
 </drink>

 <snack>
  <chips>
   <price>$4.50</price>
   <amount>60</amount>
  </chips>
 </snack>
</inventory>
If you said that pop was the ancestor of amount because pop contains amount, then you're right! Here's a graphical representation of the relationship. If you think of it just like a family tree, it becomes a lot easier!

XML Tree:

What are the other elements that are the ancestor of the highlighted amount? If you said drink and inventory, you're right! That's because drink contains amount and inventory also contains amount.

XML Tree:

Tip: The root element of an XML document is the ancestor of every element in the document. This is because all the elements are contained by the root element, by definition of a well-form XML document.

0 comments:

Post a Comment