HelloXPathSimple

■前提

ファイル"files/hello.javax.xml.xpath/HelloXpath.xml" は以下のような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>

■コード

package hello.javax.xml;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.xpath.XPath;

import javax.xml.xpath.XPathConstants;

import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class HelloXPathSimple {

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()";

XPath xpath = XPathFactory.newInstance().newXPath();

Document doc = DocumentBuilderFactory.newInstance()

.newDocumentBuilder().parse(xmlFile);

String text = (String) xpath.evaluate(xpathExpression, doc,

XPathConstants.STRING);


System.out.println(text);

}

}

■結果

0743416910