Chapter 16. XPath


Much of the code in this book has involved navigating the tree structure of an XML document to find particular nodes. For example, the XML-RPC servlet in Example 10.13 read a client request looking for int elements. Such code can become quite involved and fragile if you aren't very careful. As the code walks down the tree hierarchy, loading one child after the other, a single misplaced or misnamed element may cause the program to fail. If an element isn't where it's expected to be, then the chain of method calls that gives directions to the desired elements will be broken. What's needed is a way to specify which nodes a program needs without explicitly specifying how the program navigates to those nodes.

XPath is a fourth-generation declarative language for locating nodes in XML documents. An XPath location path specifies which nodes from the document you want. It says nothing about what algorithm is used to find these nodes. You simply pass an XPath statement to a method, and the XPath engine is responsible for figuring out how to find all of the nodes that satisfy that expression. This is much more robust than writing the detailed search and navigation code yourself using DOM, SAX, or JDOM. XPath searches often succeed even when the document format is not quite what you expected. For example, a comment in the middle of a paragraph of text may break DOM code that expects to see contiguous text. XPath wouldn't be phased by this. Many XPath expressions are resistant even to much more significant alterations, such as changing the names or namespaces of ancestor elements, reordering the children of an element, or even adding or subtracting entire levels from the tree hierarchy.

In the large, using XPath in a Java program is like using SQL in a Java program. To extract information from a database, you write a SQL statement indicating what information you want, and you ask JDBC to fetch it for you. You neither know nor care how JDBC communicates with the database. Similarly with XML, you write an XPath expression to indicate what information you want from an XML document and ask the XPath engine to fetch it, without concerning yourself with the exact algorithms XPath uses to search the XML document.



Processing XML with Java. A Guide to SAX, DOM, JDOM, JAXP, and TrAX
Processing XML with Javaв„ў: A Guide to SAX, DOM, JDOM, JAXP, and TrAX
ISBN: 0201771861
EAN: 2147483647
Year: 2001
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net