Dom4j selectNodes(arg) don't give list of nodes
Asked Answered
Z

2

8

I am using DOM4j for XML work in java, my xml is like this:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<abcd name="ab.catalog" xmlns="http://www.xyz.com/pqr" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.xyz.com/pqr ./abc.xyz.xsd">             
<efg>
......
</efg>
<efg>
.....
</efg>
</abcd>

then,

List<Node>list = document.selectNodes("/abcd/efg");

gets the size of list zero. I feel it's due to namespace specified in the xml. I tried a lot but cn't get success.

Zucchetto answered 14/1, 2013 at 11:12 Comment(0)
T
14

Unprefixed element names in XPath expressions refer to elements that are not in a namespace - they do not take account of the "default" xmlns="..." namespace declared on the document. You need to declare a prefix for the namespace in the XPath engine and then use that prefix in the expression. Here is an example inspired by the DOM4J javadocs:

Map uris = new HashMap();
uris.put("pqr", "http://www.xyz.com/pqr");
XPath xpath = document.createXPath("/pqr:abcd/pqr:efg");
xpath.setNamespaceURIs(uris);
List<Node> nodes = xpath.selectNodes(document);
Thaw answered 14/1, 2013 at 13:18 Comment(2)
@ Ian: thanxs, it works, but i have a query if i have to retrieve some more node or node value in the child to child node, then i tried as the same specified above like > for(Node node:nodes){ XPath xpath1 = document.createXPath("//edx:Name/value-"); xpath1.setNamespaceURIs(uris); Node nameNode = (Node) xpath1.selectSingleNode(node); } but it gives nameNode null. how to make it workable like dom4j. any input will be appreciable.Zucchetto
@Zucchetto //edx:Name/value- is an absolute path, which will start looking from the root node of the document that contains node. If you want edx:Name descendants of the current node then you need to use a relative path .//edx:Name/value- (with a leading dot).Thaw
H
-5

Modify your code :

List<Node>list = document.selectNodes("//abcd/efg");
Hydrosol answered 14/11, 2013 at 16:29 Comment(2)
this is not true. the // syntax has nothing to do with namespacesKeller
This answer is utterly wrong and should be deleted.Chiropractor

© 2022 - 2024 — McMap. All rights reserved.