HelloJXPath

■コード

package hello.org.apache.commons.jxpath;

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;

import org.apache.commons.jxpath.JXPathContext;

public class HelloJXPathMain {

/**

* @param args

*/

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

String xmlFile = "files/HelloXpath.xml";

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

XPathFactory factory = XPathFactory.newInstance();

XPath xpath = factory.newXPath();

XPathExpression xpath0 = xpath.compile(xpathExpression);

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

DocumentBuilderFactory domFactory = DocumentBuilderFactory

.newInstance();

domFactory.setNamespaceAware(true);

org.w3c.dom.Document doc = null;

DocumentBuilder builder = domFactory.newDocumentBuilder();

doc = builder.parse(xmlFile);

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

System.out.println(text);




// JXPathContextの生成

JXPathContext context = JXPathContext.newContext(doc);

// 存在しないXPathが指定された場合にnullを返すように設定

context.setLenient(true);


System.out.println(context.getValue("/inventory/book[@id=2]/isbn/text()"));



}

}

■ファイル(files/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

0743416910