「java」XPathを使ってXMLファイルを読み込むコード

1.Javaコード
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class XPathDemo {
public static void main(String[] args) throws ParserConfigurationException,
SAXException, IOException, XPathExpressionException {
//documentオブジェクト作成
DocumentBuilder builder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = builder.parse(new File(“bookstore.xml"));
// XPathオブジェクト作成
XPath xpath = XPathFactory.newInstance().newXPath();
// ノードの値
String webTitle = (String) xpath.evaluate(
“/bookstore/book[@category=’WEB’]/title/text()", document,
XPathConstants.STRING);
System.out.println(webTitle);
System.out.println(“******************************");
// ノードの属性
String webTitleLang = (String) xpath.evaluate(
“/bookstore/book[@category=’WEB’]/title/@lang", document,
XPathConstants.STRING);
System.out.println(webTitleLang);
System.out.println(“******************************");
// ノードオブジェクト
Node bookWeb = (Node) xpath.evaluate(
“/bookstore/book[@category=’WEB’]", document,
XPathConstants.NODE);
System.out.println(bookWeb.getNodeName());
System.out.println(“******************************");
// ノードリスト
NodeList books = (NodeList) xpath.evaluate(“/bookstore/book", document,
XPathConstants.NODESET);
for (int i = 0; i < books.getLength(); i++) {
Node book = books.item(i);
System.out.println(xpath.evaluate(“@category", book,
XPathConstants.STRING));
}
System.out.println(“******************************");
}
}

2.bookstore.xml
<?xml version="1.0″ encoding="utf-8″ ?>
<bookstore>
<book category="COOKING">
<title lang="en">AA</title>
<author>AA1</author>
<year>2016</year>
<price>11</price>
</book>
<book category="CHILDREN">
<title lang="en">BBr</title>
<author>BB1</author>
<year>2016</year>
<price>12</price>
</book>
<book category="WEB">
<title lang="en">CC</title>
<author>CC1</author>
<year>2016</year>
<price>13</price>
</book>
</bookstore>

Java

Posted by arkgame