22

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

Grammin
  • 11,808
  • 22
  • 80
  • 138

1 Answers1

45

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.

Marco
  • 700
  • 1
  • 14
  • 26
robert_x44
  • 9,224
  • 1
  • 32
  • 37
  • Thank you very much for another awesome answer RD01. – Grammin Jan 14 '11 at 15:49
  • 2
    That seems to work only for "namespace-aware" `DocumentBuilderFactory` objects, as DOM level 1-created elements do not have a `localName`... – Lukas Eder Jul 07 '12 at 14:36
  • Also, if you have a document with items with no namespace at all, it still can't find them... :( – Peterdk Sep 12 '13 at 18:58
  • 1
    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... – Bludwarf Sep 30 '14 at 13:57
  • 2
    note that you have to call DocumentBuilderFactory.setNamespaceAware(true) for this to work. – Wheezil Oct 16 '16 at 20:20
  • It Worked ..but be sure to add DocumentBuilderFactory.setNamespaceAware(true) just after creating the dbfactory obj like DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); – Chinmoy Jan 11 '17 at 13:33