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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thank you very much for another awesome answer RD01.
That seems to work only for "namespace-aware" DocumentBuilderFactory objects, as DOM level 1-created elements do not have a localName...
Also, if you have a document with items with no namespace at all, it still can't find them... :(
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...
note that you have to call DocumentBuilderFactory.setNamespaceAware(true) for this to work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.