The XPath language provides a simple, concise syntax for selectingnodes from an XML document. XPath also provides rules for converting anode in an XML document object model (DOM) tree to a boolean, double,or string value. XPath is a W3C-defined language and an official W3Crecommendation; the W3C hosts the XML Path Language (XPath) Version1.0 specification.
XPath Context
XPath location paths may be relative to a particular node in thedocument, known as the context
. Consider the followingXML document:
<widgets> <widget> <manufacturer/> <dimensions/> </widget> </widgets>
The <widget>
element can be selected with thefollowing XPath API code:
// parse the XML as a W3C Document DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(new File("/widgets.xml")); XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "/widgets/widget"; Node widgetNode = (Node) xpath.evaluate(expression, document, XPathConstants.NODE);
With a reference to the <widget>
element, arelative XPath expression can now written to select the<manufacturer>
child element:
XPath xpath = XPathFactory.newInstance().newXPath(); String expression = "manufacturer"; Node manufacturerNode = (Node) xpath.evaluate(expression, widgetNode, XPathConstants.NODE);