2011-05-17 68 views
1

嗨,我想从XPath查询得到的数据的Java越来越元素

Element location = (Element) doc.query("//location[location_name='"+ locationName +"']/*").get(0).getDocument().getRootElement(); 
System.out.println(location.toXML()); 

Element loc = location.getFirstChildElement("location"); 
System.out.println(loc.getFirstChildElement("location_name").getValue()); 

但无论怎样我选择我总是得到1个节点(其becouse .get(0)),但我不知道如何选择节点,其被查询选中。

我发现我应该将节点强制转换为元素(XOM getting attribute from Node?),但这里展示了如何选择第一个节点。

回答

4

呼叫getParent()在结果中的第一个元素:

Builder parse = new Builder(); 
Document xml = parse.build("/var/www/JAVA/toForum.xml"); 

System.out.println(xml.query("//location[@id=83]/*").get(0).getParent().toXML()); 

产生以下输出:

<location id="83"> 
    <location_name>name</location_name> 
    <company_name>company a</company_name> 
    <machines> 
    <machine id="12">A</machine> 
    <machine id="312">B</machine> 
    </machines> 
</location> 
+1

哪里已经这么久了:) +50 4 U – 2011-06-07 18:46:48

0

目前还不清楚(至少对我而言)究竟需要做些什么。从你的查询中,你应该得到符合给定条件的节点列表。您将获得NodeList,然后您可以遍历此NodeList,并以getNodeValue为例获取每个节点的内容。

+0

我想要得到的属性,但不知道怎么样?和其余的值,其中一个获得'Nodes location = doc.query(“// location [location_name ='”+ locationName +'']/*“); \t location.get(7).getValue();'现在 – 2011-05-17 08:16:15

+0

http://download.oracle.com/javase/6/docs/api/org/w3c/dom/Node.html – jdevelop 2011-05-17 09:01:54

+0

好吧,但如何获得选定节点?? – 2011-05-17 09:15:41

2

您对getDocument()的调用正在返回整个XML文档。

query()的调用返回一个Nodes对象,该对象直接包含对之后节点的引用。

如果更改为

Element location = (Element)doc.query(
      "//location[location_name='"+ locationName +"']/*").get(0); 

System.out.println(location.getAttribute("location_name").getValue()); 

应该是确定

编辑(由extraneon)

本身一些额外的解释不值得回答的: 这样做

Element location = 
    (Element) doc.query("//location[location_name='" 
         + locationName +"']/*").get(0) 
      .getDocument().getRootElement(); 

哟你搜索树并获取请求的节点。但是你可以在你想要的元素上调用getDocument().getRootNode(),这会给你文档的最高层节点。

上述查询因此可以简化为:

Element location = (Element)doc.getRootElement(); 

未绿洲省你意。

这有点像bungie跳跃。你走到你需要的地方(元素),但立即回到你来自的地方(根元素)。

+0

谢谢'extraneon' :) – 2011-06-03 08:12:13