在Java中查找没有适当名称空间的Node中的元素 [英] Find elements in a Node without the proper namespace, in Java
问题描述
所以我有一个在这里声明的xml文档:
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);
然后我有一个函数,我在其中传递一个字符串,我想将该字符串与xml中的元素进行匹配:
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);
}
问题是当 str
进入时,其中没有任何名称空间,因此我要测试的xml是:
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>
和 str
将成为节点.所以nodelist现在为null,因为它期望tns:node但我传入了node.而且我知道忽略名称空间不是很好,但在这种情况下很好.我的问题是我不知道如何在忽略命名空间的同时在Node上搜索元素.我还考虑过将名称空间添加到出现的str中,但是我也不知道该怎么做.
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.
任何帮助将不胜感激,
谢谢-乔什
推荐答案
为匹配名称为'str'的所有节点,而与命名空间无关,请使用以下命令:
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(...).
编辑:此外,@ Wheezil如何在注释中正确说明,您必须调用 DocumentBuilderFactory.setNamespaceAware(true)
才能正常工作,否则命名空间将无法正常工作被发现.
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.
这篇关于在Java中查找没有适当名称空间的Node中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!