【问题标题】:xml parse - xpath clarification in Javaxml 解析 - Java 中的 xpath 说明
【发布时间】:2016-08-12 06:55:34
【问题描述】:

我应该如何从下面的 xml 中获取 Link

XML 内容

<document-instance system="abc.org" number-of-pages="6" desc="Drawing" link="www.google.com">
        <document-format-options>
          <document-format>application/pdf</document-format>
          <document-format>application/tiff</document-format>
        </document-format-options>
        <document-section name="DRAWINGS" start-page="1" />
      </document-instance>

之后我遍历更新 desc 属性我很挣扎

 XPathExpression firstPageUrl = xPath.compile("//document-instance/@desc=\"Drawing\"]");

预期输出:检索链接值

www.google.com

【问题讨论】:

  • 您应该查询@link 而不是@desc=["drawing"]

标签: java xml xml-parsing for-xml-path


【解决方案1】:
    File file = new File("path to file");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(file);
    XPath xPath = XPathFactory.newInstance().newXPath();

    String expression = "//document-instance/@link";
    Node node = (Node) xPath.compile(expression).evaluate(doc, XPathConstants.NODE);
    String url= node.getTextContent();

【讨论】:

  • 前导“//”是完全没有必要的 - 如果您知道文档实例是最外层元素,则无需搜索整个文档。
猜你喜欢
  • 1970-01-01
  • 2014-05-10
  • 2016-10-21
  • 2013-11-25
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 2015-06-17
  • 2010-09-25
相关资源
最近更新 更多