【问题标题】:How to retrieve values of attributes in nodelist如何检索节点列表中的属性值
【发布时间】:2015-09-29 04:02:31
【问题描述】:

对于下面的 xml 文件,我想检索对应于 lat = 53.0337395 的 id 的值,并且在 xml 中有两个 id 的 lat = 53.0337395。如下所示,为了实现这一点,我编写了以下代码,但在运行时我收到#NUMBER cannt be converted into a nodelist

请告诉我如何解决它

String expr0 = "count(//node[@lat=53.0337395]//@id)";
xPath.compile(expr0);
NodeList nodeList = (NodeList) xPath.compile(expr0).evaluate(document, 
XPathConstants.NODESET);
System.out.println(nodeList.getLength());

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="25779111" lat="53x.0334062" lon="8x.8461545"/>
<node id="25779112" lat="53x.0338904" lon="8x.846314"/>
<node id="257791191" lat="53.0337395" lon="8x.8489255"/>
<tag k="maxspeed" v="30x"/> 
<tag k="maxspeed:zone" v="yes"/>
</osm>

【问题讨论】:

  • String expr0 = "count(//node[@lat=53.0337395]//@id)"; 在你的情况下应该返回 2,你说 2 应该是一个 nodeList

标签: java xml dom xpath sax


【解决方案1】:

如果您想获取节点列表,我不确定您为什么要使用count()count() 将返回一个数字,而不是列表)。试试这个:

String expr0 = "/osm/node[@lat=53.0337395]/@id";
NodeList nodeList = (NodeList) xPath.compile(expr0).evaluate(document,
                                                             XPathConstants.NODESET);
System.out.println(nodeList.getLength());

这是一个使用您的 XML 文件作为输入的完整可编译示例:

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class IdFinder
{
    public static void main(String[] args)
            throws Exception
    {
        File fXmlFile = new File("C:/Users/user2121/osm.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document document = dBuilder.parse(fXmlFile);

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

        String expr0 = "/osm/node[@lat=53.0337395]/@id";
        NodeList nodeList = (NodeList) xPath.compile(expr0).evaluate(document, XPathConstants.NODESET);

        System.out.println("Matches: " + nodeList.getLength());
        for (int i = 0; i < nodeList.getLength(); i++) {
            System.out.println(nodeList.item(i).getNodeValue());
        }
    }
}

这个的输出是:

比赛:2 25779119 257791191

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-10
    • 2019-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多