所以我有一个在这里声明的 xml 文档:
DocumentBuilder dBuilder = dbFactory_.newDocumentBuilder();
StringReader reader = new StringReader(s);
InputSource inputSource = new InputSource(reader);
doc_ = dBuilder.parse(inputSource);
然后我有一个函数,我在其中传递一个字符串,我想将其与我的 xml 中的元素匹配:
void foo(String str)
{
NodeList nodelist = doc_.getDocumentElement().getElementsByTagName(str);
}
问题是当 str
它没有任何类型的命名空间,因此我要测试的 xml 是:
<Random>
<tns:node />
</Random>
并且 str
将是节点。所以节点列表现在为空,因为它期望 tns:node 但我传入了节点。我知道忽略名称空间不好,但在这种情况下它很好。我的问题是我不知道如何在忽略命名空间的同时在节点中搜索元素。我还考虑过将命名空间添加到传入的 str 中,但我也不知道该怎么做。
任何帮助将不胜感激,
谢谢,-乔什
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)
为了匹配名称为“str”的所有节点,无论命名空间如何,请使用以下命令:
通配符“*”将匹配任何命名空间。请参阅Element.getElementsByTagNameNS(...)。
编辑:另外,@Wheezil 在评论中如何正确说明,您必须调用
DocumentBuilderFactory.setNamespaceAware(true)
才能使其工作,否则将无法检测到命名空间。In order to match all nodes whose name is 'str' regardless of namespace use the following:
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.