2015-07-10 82 views
1

中的屬性值,我想檢索對應於lat = 53.0337395的ids值,在xml中有兩個id = lat.053.0337395的id。如下圖所示,要實現這一點,我寫了下面的代碼,但在運行時我收到#NUMBER cannt be converted into a nodelist如何檢索下列xml文件的節點列表

請讓我知道如何解決這個問題

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> 
+2

'字符串expr0 =「計數( //node[@lat=53.0337395] // @ id)「;'在你的情況下應該返回2,並且你說2應該是一個nodeList –

回答

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()); 
     } 
    } 
} 

的這個輸出是:

 
Matches: 2 
25779119 
257791191