javaxmldom4j

dom4j selectSingleNode return null value


XML File:

<?xml version="1.0" encoding="UTF-8"?>
<INVOICE xmlns:xs="http://www.w3.org/2001/XMLSchema"
         xmlns:fo="http://www.w3.org/1999/XSL/Format">
   <HEADER>      
...

My (working) code that read the xml:

File inputFile = new File(filepath.toString());
SAXReader reader = new SAXReader();
Document document = reader.read(inputFile);
Node node = document.selectSingleNode("//INVOICE/HEADER");

They changed the xml file like this:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Invoice xmlns="http://com.spx/commerce/rasp/transform">
    <Header>
...

I've (simply) changed the code

Node node = document.selectSingleNode("//Invoice/Header");

But it doesn't work, it returns null. How should I change the code?

Thanks in advance

Cheers

Update

So it's a matter about namespace. I'm trying something like this

Namespace ns = new Namespace("","http://com.spx/commerce/rasp/transform");
document.add(ns);
document.selectSingleNode("//Invoice/Header");

or

XPath xpath = DocumentHelper.createXPath( "//Invoice/Header");
Map<String, String> map = new HashMap<String, String>();
map.put("", "http://com.spx/commerce/rasp/transform");
xpath.setNamespaceURIs(map);
Element tagElement = ((Element)xpath.selectSingleNode(document));

But I'm still having null/empty value

I suppose I'm missing something about namespace...

Solution

HashMap map = new HashMap();
map.put("t", "http://com.spx/commerce/rasp/transform");                   
XPath xpath = DocumentHelper.createXPath( "//t:Invoice/t:Header");
xpath.setNamespaceURIs(map);
Element tagElement = ((Element)xpath.selectSingleNode(document));

Solution

  • It's not only the local name of the node that's changed, the namespace has changed too. You need to bind a prefix to the namespace and select using that prefix.