XPath - Expressions
XPath can locate any type of information in an XML document with one line of code. These one liners are referred to as "expressions," and every piece of XPath that you write will be an expression. Just to make it crystal clear, here's the definition of an expression as it relates to our usage.- expression: In programming, a line of source code that returns a value when executed. ~Computer Desktop Encyclopedia
XPath - Our Sample XML File
We have slightly modified our lemonade XML document to make it more interesting. Our new XML document is lemonade2.xml, and it has had a couple new attributes and elements added to it, which we have highlighted.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 - A Simple XPath Expression
An XPath expression describes the location of an element or attribute in our XML document. By starting at the root element, we can select any element in the document by carefully creating a chain of children elements. Each element is separated by a slash "/".For example, if we wanted to know the number of chips we have in stock(element amount) in lemonade2.xml, the XPath expression would be:
XPath Expression:
inventory/snack/chips/amount
- We specified the root node, inventory, at the beginning of our XPath expression.
- We chose inventory's child element, snack, because it is on the pathway toward our goal, "number of chips in stock".
- We chose snack's child element chips.
- Finally, we chose chips' child element amount, or in other words, "number of chips in stock".
0 comments:
Post a Comment