tags:

views:

62

answers:

2

I get a XML file from website (http://www.abc.com/),

URL is: http://www.abc.com/api/api.xml

content is:

<?xml version="1.0" encoding="utf-8"?>
<root xmlns="http://www.abc.com/"&gt;
    <name>Hello!</name>
</root>

it has xmlns="http://www.abc.com/" in XML file,

now, I using JDOM XPath to get text Hello!

XPath xpath = XPath.newInstance("/root/name/text()");
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new URL("http://www.abc.com/api/api.xml"));

System.out.println(xpath.valueOf(doc)); //nothing to print...

I test to remove xmlns="http://www.abc.com/" from XML file, it's be work!

how to change my java code to get Hello!, if xmlns="http://www.abc.com/" exist?

(I can't chagne this XML file)

thanks for help :)

+1  A: 

You'll need to make the query aware of the xml namespace. This answer here looks like it will do the trick:

Default Xml Namespace JDOM and XPATH

You might also change your query to use local-name to ignore namespaces:

XPath xpath = XPath.newInstance("/*[local-name() = 'root']");

That should return the node named root. That is, if it supports it and I typed it correctly! :) I'm not familiar with java API's for XML + XPATH.

Be aware that xml namespaces exist to distinguish node 'root' from any other node named 'root'. Just like class/package namespaces. Ignoring them could lead to a name collision. Your milage may vary.

HTH, Zach

Zach Bonham
+1  A: 

I have not done this recently. But a quick search found

http://illegalargumentexception.blogspot.com/2009/05/java-using-xpath-with-namespaces-and.html

which point to the usage of a XPathFactory:

NamespaceContext context = new NamespaceContextMap("http://www.abc.com/" );

Or, you could use Zach's answer and just ignore the given namespace (if i understood him right). This could lead to problems if there are more 'root' nodes at the same hierarchy level..

bert