gpt4 book ai didi

java - 如何使用 XMLDog 从 xml 文件中检索值

转载 作者:行者123 更新时间:2023-12-02 04:29:49 25 4
gpt4 key购买 nike

我正在学习如何通过 xpath 使用 SAX this tutorial 。我编写了下面的代码,但它返回 null 而不是显示 '30'

请告诉我如何解决这个问题,还有其他库可以将 SAX 与 Xpath 结合使用吗?

代码:

DefaultNamespaceContext nsContext = new DefaultNamespaceContext(); // an implementation of javax.xml.namespace.NamespaceContext
nsContext.declarePrefix("xsd", Namespaces.URI_XSD);

XMLDog dog = new XMLDog(nsContext);
XPathResults results = dog.sniff(new InputSource("c:\\brem.xml"));

Expression xpath1 = dog.addXPath("//node[@lat='53.0334062'] [@lon='8.8461545']/following-sibling::tag[1]/@v");
Log.d("", "", ""+results.getResult(xpath1));

xml:

<?xml version='1.0' encoding='utf-8' ?>
<osm>
<node id="25779111" lat="53.0334062" lon="8.8461545"/>
<node id="25779112" lat="53.0338904" lon="8.846314"/>
<node id="25779119" lat="53.0337395" lon="8.8489255"/>
<tag k="maxspeed" v="30"/>
<tag k="maxspeed:zone" v="yes"/>
<node id="25779114" lat="53.334062" lon="8.841545"/>
<node id="25779117" lat="53.038904" lon="8.84614"/>
<node id="25779110" lat="53.033795" lon="8.489255"/>
<tag k="maxspeed" v="32"/>
<tag k="maxspeed:zone" v="no"/>
</osm>

最佳答案

您应该在嗅探之前添加 xpath:

DefaultNamespaceContext nsContext = new DefaultNamespaceContext();

XMLDog dog = new XMLDog(nsContext);
Expression xpath1 = dog.addXPath("//node[@lat='53.0334062'] [@lon='8.8461545']/following-sibling::tag[1]/@v");
XPathResults results = dog.sniff(new InputSource(""c:\\brem.xml"));
List<NodeItem> list = (List<NodeItem>)results.getResult(xpath1);
System.out.println(list.isEmpty() ? null : list.get(0).value);

打印:

30

关于java - 如何使用 XMLDog 从 xml 文件中检索值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31613435/

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