我正在尝试解析包含命名空间元素的常规 XML。但是, getElementsByTagNameNS() 始终返回空 NodeList。例如,在下面的代码中,我硬编码了一些 SAML 文本(因为它具有命名空间并且可用),它返回一个空的 NodeList:
NodeList test() {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
documentBuilderFactory.setNamespaceAware(true);
documentBuilderFactory.setValidating(false);
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(new StringInputStream(
"<samlp:Response xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:2.0:assertion\">\n" +
" <saml:Assertion>\n" +
" </saml:Assertion>\n" +
"</samlp:Response>"
));
return document.getElementsByTagNameNS("saml", "Assertion");
}
问题是,我已将其设置为命名空间感知。据我所知,这应该返回一个带有一个结果的 NodeList。
编辑
类似的问题有很多,但都是由忘记启用命名空间感知的人提出的。
编辑
为了精确起见,我使用开放的 JDK 1.8.0.151 运行了这段代码。
最佳答案
getElementsByTagNameNS() 的第一个参数是命名空间 URI,而不是前缀。所以应该是这样的
return document.getElementsByTagNameNS("urn:oasis:names:tc:SAML:2.0:assertion", "Assertion");
关于java - 返回空 NodeList 的命名空间感知文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48086496/