如何在Java中使用XPath读取XML [英] How to read XML using XPath in Java

查看:174
本文介绍了如何在Java中使用XPath读取XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Java中使用XPath读取XML数据,因此对于我收集的信息,我无法根据我的要求解析XML。

I want to read XML data using XPath in Java, so for the information I have gathered I am not able to parse XML according to my requirement.

这里是我想做什么:

通过URL从在线获取XML文件,然后使用XPath解析它,我想在其中创建两个方法。一个是我输入一个特定的节点属性id,我得到所有子节点的结果,第二个假设我只想获得一个特定的子节点值

<?xml version="1.0"?>
<howto>
  <topic name="Java">
      <url>http://www.rgagnonjavahowto.htm</url>
  <car>taxi</car>
  </topic>
  <topic name="PowerBuilder">
       <url>http://www.rgagnon/pbhowto.htm</url>
       <url>http://www.rgagnon/pbhowtonew.htm</url>
  </topic>
  <topic name="Javascript">
        <url>http://www.rgagnon/jshowto.htm</url>
  </topic>
 <topic name="VBScript">
       <url>http://www.rgagnon/vbshowto.htm</url>
 </topic>
 </howto>

在上面的示例中,如果我通过@name和一个函数搜索,我想读取所有元素我只想要来自@name'Javascript'的网址只返回一个节点元素。

In above example I want to read all the elements if I search via @name and also one function in which I just want the url from @name 'Javascript' only return one node element.

推荐答案

你需要的东西是这个:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(<uri_as_string>);
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile(<xpath_expression>);

然后你打电话给 expr.evaluate()传入该代码中定义的文档和您期望的返回类型,并将结果转换为结果的对象类型。

Then you call expr.evaluate() passing in the document defined in that code and the return type you are expecting, and cast the result to the object type of the result.

如果您需要特定方面的帮助XPath表达式,您应该将其视为单独的问题(除非这是您在这里首先提出的问题 - 我理解您的问题是如何在Java中使用API​​)。

If you need help with a specific XPath expressions, you should probably ask it as separate questions (unless that was your question in the first place here - I understood your question to be how to use the API in Java).

(对评论的回应):这个XPath表达式将为您提供PowerBuilder下第一个URL元素的文本:

(Response to comment): This XPath expression will get you the text of the first URL element under PowerBuilder:

/howto/topic[@name='PowerBuilder']/url/text()

这将给你第二个:

/howto/topic[@name='PowerBuilder']/url[2]/text()

您可以使用以下代码获得:

You get that with this code:

expr.evaluate(doc, XPathConstants.STRING);

如果您不知道给定节点中有多少个URL,那么您应该做点什么像这样:

If you don't know how many URLs are in a given node, then you should rather do something like this:

XPathExpression expr = xpath.compile("/howto/topic[@name='PowerBuilder']/url");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

然后遍历NodeList。

And then loop over the NodeList.

这篇关于如何在Java中使用XPath读取XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆