XML Tree - Parent
In real life a person can have multiple parents, especially if the parents divorce and remarry. Thankfully, the relationship in XML is less complicated.
Each XML element can have at most one parent. XML can pull this off because an XML element does not require another element to reproduce (OK, that was a silly joke; I apologize).
Element A is the parent of element B when :
- Element B is contained within element A and element A is exactly one level above element B.
In other words, the parent element A is the ancestor of element B. Below is an example with 3 parent relationships.
The element d is contained by element a, b and c, but only the element c is exactly one level up in the XML Tree, making c the parent of d.
Questions: What are the other parent relationships in this XML document?
- b is the parent of c
- a is the parent of b
Who's the Parent?
Usually an XML document is indented in such a way as to make finding an element's parent very easy. However, if the indentation is done poorly there is a simple trick to determine an element's parent. Start at the element in question and move up towards the start of the file. The first opening tag that you reach that does not have a corresponding closing tag is the parent.
Can you find the parent element of lemonade in our lemonade.xml document.?
XML Code, lemonade.xml:
drink is the parent of lemonade.
Here is a the XML Tree of the parental relationship between drink and lemonade.
Bonus: Which element is the parent of snack?
Download Tizag.com's XML Book
If you would rather download the PDF of this tutorial, check out our
XML eBook from the Tizag.com store.
Found Something Wrong in this Lesson?
Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!