2011年3月1日火曜日

JavaでXPathを使ったことがあった

<?xml version="1.0" encoding="UTF-8"?>
<hello>
    <item>
        <world attr="value1"/>
    </item>
    <item>
        <world attr="value2"/>
    </item>
</hello>
import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XPathSample {
    public static void main(String[] args) throws Exception {
        XPathExpression xpath =
            XPathFactory.newInstance()
            .newXPath()
            .compile("//world[@attr='value2']");

        Document document =
            DocumentBuilderFactory.newInstance()
            .newDocumentBuilder()
            .parse(new File("hello.xml"));

        NodeList nodeList = (NodeList) xpath.evaluate(document, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            NamedNodeMap attributes = node.getAttributes();
            String value = attributes.getNamedItem("attr").getNodeValue();
            System.out.println(value);
        }
    }
}

0 件のコメント:

コメントを投稿