XPath - Descendants "//"
As you know, the slash "/" is used to separate parent from child in our XPath expressions. However, when you put two slashes together "//", it does something completely different. Two slashes are used to select the descendants of an element.This lesson will teach you how to advance your XPath knowledge and save time with the descendant double-slash "//".
We will be using our lemonade2.xml file, which you can download.
XML Code, lemonade2.xml:
<inventory> <drink> <lemonade supplier="mother" id="1"> <price>$2.50</price> <amount>20</amount> </lemonade> <pop supplier="store" id="2"> <price>$1.50</price> <amount>10</amount> </pop> </drink> <snack> <chips supplier="store" id="3"> <price>$4.50</price> <amount>60</amount> <calories>180</calories> </chips> </snack> </inventory>
XPath - Choosing Descendants
Although relative and absolute paths will let you select anything you want in your XML document, they can sometimes be quite time-consuming. If you wanted to select each price element that was a descendant of drink, you would have to write two absolute XPath expressions.Absolute XPath Expression:
inventory/drink/lemonade/price inventory/drink/pop/price
Relative XPath Expression:
drink/lemonade/price drink/pop/price
The "//" sequence will save you a lot of time. If you wanted to select every price element that has a drink ancestor, this expression would get the job done.
Relative Location with Descendants XPath Expression:
drink//price
- We start our expression with the relative location drink.
- We tell XPath that we want to select from the descendants of drink with "//"
- We specify that we specifically want to select the price descendant.
- We pat ourselves on the back for getting the job done efficiently!
0 comments:
Post a Comment