XML Parent

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

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.

XML Code:

<a>
	<b>
		<c>
			<d>
			</d>
		</c>
	</b>
</a>

The element d is contained by element ab 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?

Answer:

  • 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:

<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>

drink is the parent of lemonade.

Here is a the XML Tree of the parental relationship between drink and lemonade.

XML Tree:

Bonus: Which element is the parent of snack?

Answerinventory.