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

以下是我想做的:

Get XML file from online via its URL, then use XPath to parse it, I want to create two methods in it. One is in which I enter a specific node attribute id, and I get all the child nodes as result, and second is suppose I just want to get a specific child node value only

<?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’中的url只返回一个 node 元素.

推荐答案

你需要这样的东西:

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(),传入该代码中定义的文档和预期的返回类型,并将结果强制转换为结果的对象类型.

如果您需要有关特定XPath表达式的帮助,您可能应该单独问它(除非这是您在这里首先提出的问题-我认为您的问题是如何在Java中使用API).

编辑:(回复注释):此XPath表达式将获得PowerBuilder下第一个URL元素的文本:

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

这将为您带来第二个:

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

你可以通过以下代码得到:

expr.evaluate(doc, XPathConstants.STRING);

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

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

然后在NodeList上循环.

Java相关问答推荐

获取拦截器内部的IP地址

Jooq隐式地将bigint转换为数字,并且索引不起作用

Spring Webocket:尽管凭据设置为False,但MLhttpsify和Fetch请求之间的CORS行为存在差异

当耗时的代码完成时,Circular ProgressIndicator显示得太晚

在Java 8之后,HashMap的最坏情况下时间复杂度仍然是O(n)而不是O(log n)?

Java函数式编程中的双值单值映射

基本时态运算的ISO-8601周数据表示法

Chunk(Int)已弃用并标记为要删除

通过移动一个类解决了潜在的StubbingProblem.它怎麽工作?

在向WebSphere中的文档添加元素时iText挂起

try 从REST API返回对象列表时出错

在Java 15应用程序中运行Java脚本和Python代码

使用htmlunit和java单击按钮

如何在Java中为thunk创建映射器函数

错误:不兼容的类型:Double不能转换为Float

我可以在@Cacheable中使用枚举吗

通过/失败的参数化junit测试方法执行数

rest api服务 spring 启动中出现IllegalFormatConversionException

获取月份';s在java中非UTC时区的开始时间和结束时间

可以';不要在Intellij IDEA中使用最新的Java版本(JDK 21)