【问题标题】:Error in xpath compile evaluate queryxpath 编译评估查询中的错误
【发布时间】:2015-06-29 09:48:28
【问题描述】:

我有以下 XML:

<?xml version="1.0" encoding="UTF-8"?>
<data>
   <DataType1>
      <val1 />
      <val2 />
   </DataType1>
   <DataType2>
      <val21 />
      <val22 />
      <RetrieveThis1>test1</RetrieveThis1>
      <RetrieveThis2>test2</RetrieveThis2>
      <RetrieveThis3>test3</RetrieveThis3>
   </DataType2>
</data>

我需要在 java 中检索值 test1、test2 和 test3。 我正在尝试按如下方式使用 xPath 查询:

String test1Value = xpath.compile("/data/DataType2/RetrieveThis1").evaluate(inputXML);
String test2Value = xpath.compile("/data/DataType2/RetrieveThis2").evaluate(inputXML);
String test3Value = xpath.compile("/data/DataType2/RetrieveThis3").evaluate(inputXML);

它没有给出结果。您能否建议我在编译查询中传递的 XPathExpresstion 是否正确。

非常感谢您。

【问题讨论】:

  • 任何错误或只是空的结果? Node node = (Node) xpath.compile(expression).evaluate(inputXML, XPathConstants.NODE); String value = node.getNodeValue(); 怎么样
  • 不走运。它正在抛出 ClassCastException :(
  • 我还有另一项工作。如果我们在字符串中有整个 XML。如何使用 Java 的字符串操作函数在 之间查找文本?请大家帮忙:'(
  • 这是另一个问题。请在下面找到我的答案,它应该可以工作。
  • 问题是我的 XML 文件内容包含在一个字符串中,我将其解析为 XML,如下所示:org.w3c.dom.Document XMLDomDocument = (org.w3c.dom.Document)builder。解析(新输入源(新 StringReader(DomXMLAsString)));但是,由于没有这样创建 XML 文件,因此该语句给出了异常

标签: xml xpath


【解决方案1】:

此代码适用于我

String documentXmlAsString = readSomeXMLFromString();
final DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder =  builderFactory.newDocumentBuilder();
final InputSource is = new InputSource(new StringReader(documentXmlAsString));
is.setEncoding("UTF-8");
final Document document = builder.parse(is);
final XPath xpath = XPathFactory.newInstance().newXPath();
final String test3Value = xpath.compile("/data/DataType2/RetrieveThis3").evaluate(document);

System.out.println(test3Value);

将打印 test3

【讨论】:

  • 问题是我的 XML 文件内容包含在一个字符串中,我将其解析为 XML,如下所示:org.w3c.dom.Document XMLDomDocument = (org.w3c.dom.Document)builder。解析(新输入源(新 StringReader(DomXMLAsString)));但是,由于没有这样创建 XML 文件,因此该语句给出了异常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
相关资源
最近更新 更多