Loading...

java でxml xpathで、ネームスペース

Java XPath API


java5以上です。
ネームスペースを使ってXPathを使って値をとるサンプルです。

package a;

import java.io.IOException;

import java.net.URISyntaxException;

import javax.xml.XMLConstants;
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.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;

public class TestMain {

public static void main(String[] args) throws SAXException, IOException,
XPathExpressionException, ParserConfigurationException,
URISyntaxException {

DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setNamespaceAware(true);// 重要!!
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = builder.parse(TestMain.class.getResource("a.xml")
.toURI().toString());
a(doc);
System.out.println("----");
b(doc);

}

static void a(Document doc) throws XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
XPathExpression expr = xpath
.compile("//book[@year='1969']/title/text()");

Object result = expr.evaluate(doc, XPathConstants.STRING);
System.out.println(result);

}

static void b(Document doc) throws XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
xpath.setNamespaceContext(new MyNamespaceContext());

XPathExpression expr = xpath
.compile("//my:book[@year='2007']/my:title/text()");
Object result = expr.evaluate(doc, XPathConstants.STRING);
System.out.println(result);
}

static class MyNamespaceContext implements NamespaceContext {
public String getNamespaceURI(String prefix) {
if (prefix == null)
throw new NullPointerException("Null prefix");
else if ("my".equals(prefix))
return "http://deiji.jp";
else if ("xml".equals(prefix))
return XMLConstants.XML_NS_URI;
return XMLConstants.NULL_NS_URI;
}

public String getPrefix(String uri) {
throw new UnsupportedOperationException();
}

public Iterator getPrefixes(String uri) {
throw new UnsupportedOperationException();
}

}

}



<my xmlns="http://deiji.jp">
<book year="1969">
<title>aaaaa</title>
<author>nakawaka</author>
</book>
<book year="2007">
<title>bbbbb</title>
<author>shigeto</author>
</book>
</my>
リアクション: 
xpath 4541142061851497763

コメントを投稿

ホーム item

このブログを検索

Random Posts

Popular Posts

Labels

ADS