HelloXpath

■コード

package hello.javax.xml;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.xpath.XPath;

import javax.xml.xpath.XPathConstants;

import javax.xml.xpath.XPathExpression;

import javax.xml.xpath.XPathFactory;

public class HelloXpath {

public static void main(String[] args) throws Exception {

String xmlFile = "files/hello.javax.xml.xpath/HelloXpath.xml";

String xpathExpression = "/inventory/book[@id=2]/isbn/text()";

XPathFactory factory = XPathFactory.newInstance();

XPath xpath = factory.newXPath();

XPathExpression xpath0 = xpath.compile(xpathExpression);

org.w3c.dom.Document doc = null;

// XML 読み込みクラスの初期化

DocumentBuilderFactory domFactory = DocumentBuilderFactory

.newInstance();

domFactory.setNamespaceAware(true);

DocumentBuilder builder = domFactory.newDocumentBuilder();

doc = builder.parse(xmlFile);

String text = (String) xpath0.evaluate(doc, XPathConstants.STRING);

System.out.println(text);

}

}

■用意するファイル

files/hello.javax.xml.xpath/HelloXpath.xml

<inventory>

<book id="1">

<title>Snow Crash</title>

<author>Neal Stephenson</author>

<publisher>Spectra</publisher>

<isbn>0553380958</isbn>

<price>14.95</price>

</book>

<book id="2">

<title>Burning Tower</title>

<author>Larry Niven</author>

<author>Jerry Pournelle</author>

<publisher>Pocket</publisher>

<isbn>0743416910</isbn>

<price>5.99</price>

</book>

<book id="3">

<title>Zodiac</title>

<author>Neal Stephenson</author>

<publisher>Spectra</publisher>

<isbn>0553573862</isbn>

<price>7.50</price>

</book>

</inventory>

■結果

0743416910

tags

---

java xpath