【问题标题】:How to select all attribute values from a particular attribute using xpath in Java如何在 Java 中使用 xpath 从特定属性中选择所有属性值
【发布时间】:2014-03-05 12:25:14
【问题描述】:

我有以下包含 GPS 坐标的 XML 文件,我只是想知道如何在 Java 中使用 Xpath 提取轨道纬度和经度。到目前为止我试过了:

System.out.println(xpath.evaluate("/gpx/trk/trkseg/trkpt/@lat", doc));

但这仅检索第一个值?请有人告诉我如何一次性检索所有值。

非常感谢。

<gpx xmlns="http://www.topografix.com/GPX/1/1"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" creator="MapSource 6.11.3"
version="1.1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1
http://www.topografix.com/GPX/1/1/gpx.xsd">
<metadata>...</metadata>
<wpt lat="40.653792" lon="-111.922379">...</wpt>
<wpt lat="40.658111" lon="-111.919564">...</wpt>
<wpt lat="40.659546" lon="-111.917527">...</wpt>
<wpt lat="40.595857" lon="-111.910294">...</wpt>
<wpt lat="40.657349" lon="-111.918721">...</wpt>
<trk>
<name>FromParking</name>
<extensions>...</extensions>
<trkseg>
<trkpt lat="40.653782" lon="-111.922365">
    <ele>1224.376221</ele>
    <time>2009-11-19T20:00:11Z</time>
</trkpt>
<trkpt lat="40.653786" lon="-111.922350">
    <ele>1223.895508</ele>
    <time>2009-11-19T20:00:13Z</time>
</trkpt>
<trkpt lat="40.654449" lon="-111.922073">
    <ele>1224.376221</ele>
    <time>2009-11-19T20:00:22Z</time>
</trkpt>
<trkpt lat="40.654509" lon="-111.921919">
    <ele>1224.376221</ele>
    <time>2009-11-19T20:00:25Z</time>
</trkpt>
<trkpt lat="40.654618" lon="-111.921700">
    <ele>1224.856934</ele>
    <time>2009-11-19T20:00:35Z</time>
</trkpt>

【问题讨论】:

  • 您使用的是什么 XML/XPath 库?

标签: java xml xpath


【解决方案1】:

除了我在my answer to your previous question 中描述的命名空间问题之外,您的基本问题是XPath.evaluate 方法没有 QName returnType 参数会将XPath 表达式评估为字符串 ,XPath 规则说包含多个节点的节点集合的字符串值是defined to be 文档顺序集合中第一个 节点的字符串值。 p>

如果您想计算返回一组节点的 XPath 表达式,那么您必须使用一个采用 QName 的 XPath 方法,将 XPathConstants.NODESET 作为请求的返回类型传递,并将从 evaluate 返回的结果转换为org.w3c.dom.NodeList 然后您可以对其进行迭代。

【讨论】:

    【解决方案2】:

    试试这个:要检索所有 trkpt 属性,请这样做:

    String trkpt ="/gpx/trk/trkseg/trkpt";
    NodeList nodeList= (NodeList) xpath.compile(trkpt).evaluate(doc, XPathConstants.NODESET);
    
    for(int i=0; i<nodeList.getLength(); i++){
       Node node = nodeList.item(i);
       NamedNodeMap attributesMap = node.getAttributes();
    
       for (int j = 0; j< attributesMap.getLength(); j++) {            
         Node attributeNode = attributesMap.item(j);       
         String attributeName = attributeNode.getNodeName();        
         String attributeValue = attributeNode.getNodeValue();
    
         System.out.println(attributeName + "=" + attributeValue);
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-01
      • 2012-11-30
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-29
      • 1970-01-01
      相关资源
      最近更新 更多