Find elements in a Node without the proper namespace, in Java

Grammin picture Grammin · Jan 14, 2011 · Viewed 22.3k times · Source

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

Answer

robert_x44 picture robert_x44 · Jan 14, 2011

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.