gpt4 book ai didi

java - 使用java在xml中搜索结束排除

转载 作者:行者123 更新时间:2023-12-01 04:57:45 24 4
gpt4 key购买 nike

我正在尝试在 xml 文件中搜索这些事件:

<xml>  
<corpus>
<body>
<nonterminals>
<graph>
<s>
<nt id="s9_509" cat="fcl"></nt>

<nt id="s9_501" cat="pp">
<edge label="H" idref="s9_1"/>
<edge label="DP" idref="s9_502"/>
<edge label="STA" idref="s9_509"/>
<edge label="P" idref="s9_19"/>
<edge label="S" idref="s9_510"/>
<edge label="PU" idref="s9_25"/>
</nt>
</nonterminals>
</graph>
</s>
</body>
</corpus>
</xml>

我的代码是:

XPath xpath = XPathFactory.newInstance().newXPath();    
String path = "//xml//corpus//build//s//graph//nonterminals//nt";
XPathExpression expr = xpath.compile(path);
System.out.println("Query1: "+path);
Object result = expr.evaluate(document, XPathConstants.NODESET);
NodeList nodes = (NodeList) result;
System.out.println("Number of nodes: "+nodes.getLength());
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getAttributes().getNamedItem("id").getNodeValue());

这个查询正确吗?还有另一种方法可以尝试吗?如何删除节点发现结果?

最佳答案

假设这是您的 XML 的整个结构和 <xml>是你的根节点,我想说你的 XPath 应该是:

/xml/corpus/build/s/graph/nonterminals/nt

如果你想匹配每个nt节点无论它出现在文档中的哪个位置,您都可以使用:

//nt

有一些有用的免费工具可以查看 XPath 查询的结果,而无需预先编写 java:

http://xml-copy-editor.sourceforge.net/

http://www.xpathtester.com/

关于java - 使用java在xml中搜索结束排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824950/

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