Find elements in a Node without the proper namespace, in Java
Asked Answered
D

1

23

So I have a xml doc that I've declared here:

DocumentBuilder dBuilder = dbFactory_.newDocumentBuilder();
StringReader reader = new StringReader(s);
InputSource inputSource = new InputSource(reader);
doc_ = dBuilder.parse(inputSource);

Then I have a function where I pass in a string and I want to match that to an element in my xml:

void foo(String str)
{
  NodeList nodelist = doc_.getDocumentElement().getElementsByTagName(str);
}

The problem is when the str comes in it doesn't have any sort of namespace in it so the xml that I would be testing would be:

<Random>
  <tns:node />
</Random>

and the str will be node. So nodelist is now null because its expecting tns:node but I passed in node. And I know its not good to ignore the namespace but in this instance its fine. My problem is that I don't know how to search the Node for an element while ignoring the namespace. I also thought about adding the namespace to the str that comes in but I have no idea how to do that either.

Any help would be greatly appreciated,

Thanks, -Josh

Diskin answered 14/1, 2011 at 15:22 Comment(0)
A
46

In order to match all nodes whose name is 'str' regardless of namespace use the following:

NodeList nodes = doc.getDocumentElement().getElementsByTagNameNS("*", str);

The wildcard "*" will match any namespace. See Element.getElementsByTagNameNS(...).

Edit: in addition, how @Wheezil correctly stated in a comment, you have to call DocumentBuilderFactory.setNamespaceAware(true) for this to work, otherwise namespaces will not be detected.

Actaeon answered 14/1, 2011 at 15:43 Comment(6)
Thank you very much for another awesome answer RD01.Diskin
That seems to work only for "namespace-aware" DocumentBuilderFactory objects, as DOM level 1-created elements do not have a localName...Jacobah
Also, if you have a document with items with no namespace at all, it still can't find them... :(Vedette
Does someone notice that if you want to specify the URL of the namespace instead of "*", no elements are returned at all. For instance when I try to match Soap Enveloppe...Pasquale
note that you have to call DocumentBuilderFactory.setNamespaceAware(true) for this to work.Neese
It Worked ..but be sure to add DocumentBuilderFactory.setNamespaceAware(true) just after creating the dbfactory obj like DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);Elkeelkhound

© 2022 - 2024 — McMap. All rights reserved.