[Yanel-dev] Using xpath together with NamespaceContext
Michael Wechner
michael.wechner at wyona.com
Sat Jul 11 16:36:06 CEST 2009
Hi
Maybe the following code is helpful for some of you when accessing an
XML with namespace
Cheers
Michael
/**
*
*/
public getTitle(Node node) throws Exception {
Document doc = XMLHelper.readDocument(node.getInputStream());
XPath xpath = XPathFactory.newInstance().newXPath();
xpath.setNamespaceContext(new MyNamespaceContext());
title = (String) xpath.evaluate("/foo:article/foo:title", doc,
XPathConstants.STRING);;
}
/**
*
*/
class MyNamespaceContext implements javax.xml.namespace.NamespaceContext {
/**
*
*/
public String getNamespaceURI(String prefix) {
if (prefix == null) {
throw new IllegalArgumentException("No prefix provided!");
} else if (prefix.equals("foo")) {
return "http://www.yanel.org/bar/1.0";
} else {
return javax.xml.XMLConstants.NULL_NS_URI;
}
}
/**
*
*/
public String getPrefix(String namespaceURI) {
// Not needed in this context.
throw new UnsupportedOperationException();
}
/**
*
*/
public java.util.Iterator getPrefixes(String namespaceURI) {
// Not needed in this context.
throw new UnsupportedOperationException();
}
}
More information about the Yanel-development
mailing list