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

≡放荡痞女 提交于 2021-02-04 16:50:27

问题


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:


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.



来源:https://stackoverflow.com/questions/4692605/find-elements-in-a-node-without-the-proper-namespace-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!