XPath - Predicates
We have learned how to select elements and attributes in an XML document, but we haven't learned how to be eliminate unwanted items. This lesson will teach you how to impose restrictions in your XPath expressions using predicates.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 - Being Choosy with Predicates
Imagine that we wanted to select all the products from lemonade2.xml that had an amount greater than 15. With the current knowledge you have, this would be impossible and would require programming outside of XPath expression to solve this problem.The closest we could get would be to select all the products:
XPath Expression:
inventory/*/*
A predicate is similar to an If/Then statement. If our predicate is TRUE, then the element will be selected. If the predicate is FALSE, it will be excluded. What would be our predicate for this example?
Well, we want to select those amount elements that are greater than 15, so in English, our predicate would be:
- predicate: greater than 15
XPath - Predicates are in Brackets [ & ]
An XPath predicate is contained within square brackets [], and comes after the parent element of what will be tested!Because we want to test each product's amount element, we might create a separate predicate for each product: lemonade, pop and chips.
To start off simply, let's just do lemonade first using an absolute path.
Predicate XPath Expression:
inventory/drink/lemonade[amount>15]
- parent[child someTestHere]
Predicate XPath Expression:
inventory/*/*[amount>15]
Answer: lemonade and chips are selected because they both have amount elements greater than 15.
XPath - Predicates with Attributes
Besides testing the values of elements, you can also use predicates to check the values of attributes. The form pretty much the same as before, except the attribute belongs to the element before the predicate.- element[@element'sAttribute someTestHere]
Predicate XPath Expression:
inventory/*/*[@supplier='store']
XPath - Predicate Current Element .
Sometimes you don't want to select the child element or attribute, but rather, the current element. XPath lets you refer to the current element with the period ".", when placed within the predicate.If we wanted to select the amount of pop where the amount was less than 20, we would need to use a period.
Predicate XPath Expression:
inventory/drink/pop/amount[. < 20]
0 comments:
Post a Comment