NamespaceContext

■コード1

package hello.javax.xml.namespace;

import java.util.Iterator;

import javax.xml.XMLConstants;

import javax.xml.namespace.NamespaceContext;

public class MyNamespaceContext implements NamespaceContext {

@Override

public String getNamespaceURI(String prefix) {

if (prefix == null) {

throw new NullPointerException("Null prefix");

} else if ("pre".equals(prefix)) {

return "http://www.example.com/books";

} else if ("xml".equals(prefix)) {

return XMLConstants.XML_NS_URI;

}

return XMLConstants.NULL_NS_URI;

}

@Override

// This method isn't necessary for XPath processing.

public String getPrefix(String uri) {

throw new UnsupportedOperationException();

}

@Override

// This method isn't necessary for XPath processing either.

public Iterator getPrefixes(String uri) {

throw new UnsupportedOperationException();

}

}

■コード2

package hello.javax.xml.namespace;

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.w3c.dom.NodeList;

public class HelloNamespaceMain {

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

String xmlFile = "files/hello.javax.xml.namespace/hellonamespace.xml";

String xpathExpression = "//pre:book[pre:author='Neal Stephenson']/pre:title/text()";

XPathFactory factory = XPathFactory.newInstance();

XPath xpath = factory.newXPath();

xpath.setNamespaceContext(new MyNamespaceContext());

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

Object result = xpath0.evaluate(doc, XPathConstants.NODESET);

NodeList nodes = (NodeList) result;

for (int i = 0; i < nodes.getLength(); i++) {

System.out.println(nodes.item(i).getNodeValue());

}

}

}

■ファイル

<?xml version="1.0" encoding="UTF-8" ?>

<inventory xmlns="http://www.example.com/books">

<book year="2000">

<title>Snow Crash</title>

<author>Neal Stephenson</author>

<publisher>Spectra</publisher>

<isbn>0553380958</isbn>

<price>14.95</price>

</book>

<!-- more books... -->

</inventory>

■実行結果

Snow Crash