gpt4 book ai didi

java - XPath 输出不连贯

转载 作者:行者123 更新时间:2023-11-30 07:25:24 25 4
gpt4 key购买 nike

我刚刚发现了 XPath,并且正在尝试使用它来解析 XML 文件。我读了一些有关它的类(class),但我遇到了一个问题。当我尝试从文件中获取 NodeList 时,getLength() 方法始终返回 0。但是,当我尝试

document.getElementsByTagName("crtx:env").getLength()

输出是正确的(在我的例子中是 7)。我不太明白,因为我的节点列表是根据我的文档构建的,输出应该类似,不是吗?

这是我的代码的一部分:

    IFile                   f               = (IFile) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
String fileURL = f.getLocation().toOSString();
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;

try {
builder = builderFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}

Document document = null;

if (builder != null){
try{
document = builder.parse(fileURL);
System.out.println("DOCUMENT URI : " + document.getDocumentURI());
} catch (Exception e){
e.printStackTrace();
}
} else {
System.out.println("builder null");
}


XPath xPath = XPathFactory.newInstance().newXPath();

NodeList nodeList = null;

try {
nodeList = (NodeList) xPath.compile("crtx:env").evaluate(document, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
e.printStackTrace();
}

System.out.println("NODELIST SIZE : " + nodeList.getLength());
System.out.println(document.getElementsByTagName("crtx:env").getLength());

}

第一个 System.out.println() 返回一致的输出(一个好的 URI),但最后两行返回不同的数字。

如有任何帮助,我们将不胜感激。感谢您的阅读。

最佳答案

XPath 是为具有如此设置的命名空间的 XML 定义的

DocumentBuilderFactory  builderFactory  = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);

然后要使用带有命名空间前缀的路径,您需要使用 https://docs.oracle.com/javase/7/docs/api/javax/xml/xpath/XPath.html#setNamespaceContext%28javax.xml.namespace.NamespaceContext%29要绑定(bind)用于命名空间 URI 的前缀,请参阅 https://xml.apache.org/xalan-j/xpath_apis.html#namespacecontext举个例子

对于命名空间感知的 DOM,您需要更改 getElementsByTagName 调用以使用 getElementsByTagNameNS。

关于java - XPath 输出不连贯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36884909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com