XPATH

来源:互联网 发布:应用统计学专业知乎 编辑:程序博客网 时间:2024/05/01 11:17

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 thecontext. 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 DocumentDocumentBuilder 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);

0 0