如何在 Java 中从 XPath 获取元素
我想从 XPath 查询中获取数据:
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 个节点(因为 .get(0)
)。我不知道如何选择通过查询选择的节点。
我发现我应该将节点转换为 Element,(XOM 从节点获取属性? )但该链接仅显示如何选择第一个节点。
I want to get data from an XPath query:
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());
However, no matter what I choose, I always get 1 node (because of .get(0)
). I don't know how to select the node which was selected by query.
I found that I should cast the node to Element, (XOM getting attribute from Node?) but the link only shows how to select the first node.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对结果中的第一个元素调用
getParent()
:产生以下输出:
Call
getParent()
on the first element in the result:Produces the following output:
您对
getDocument()
的调用将返回整个 XML 文档。对
query()
的调用会返回一个Nodes
对象,该对象直接包含对您所在节点的引用。如果你改变
它应该没问题
编辑(由extraneon)
一些额外的解释本身不值得回答:
通过这样做,
您可以搜索树并获取所请求的节点。但是,然后您对所需的元素调用
getDocument().getRootNode()
,这将为您提供文档的最上面的节点。因此,上面的查询可以简化为:
这不是您想要的。
这有点像蹦极。您向下到达您需要到达的位置(元素),但立即返回到您来自的位置(根元素)。
The call you make to
getDocument()
is returning the entirety of the XML document.The call to
query()
returns aNodes
object directly containing references to the nodes that you are after.If you change to
it should be ok
EDIT (by extraneon)
Some extra explanation not worthy of an answer by itself:
By doing
you search through the tree and get the requested node. But then you call
getDocument().getRootNode()
on the element you want, which will give you the uppermost node of the document.The above query can thus be simplified to:
which is not wahat you intended.
It's a bit like a bungie jump. You go down to where you need to be (the element) but go immediately back to where you came from (the root element).
目前尚不清楚(至少对我来说)实际需要做什么。从您的查询中,您应该获得匹配给定条件的节点列表。您将获得 NodeList,然后您可以迭代此 NodeList 并使用 getNodeValue 获取每个节点的内容。
It's not clear (at least for me) what actually has to be done. From your query you should get list of nodes matching the given criteria. You will get NodeList and then you can iterate over this NodeList and get content of each node with getNodeValue for example.