xml解析 - Java中的xpath澄清

时间:2016-08-12 06:55:34

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

我应该如何从下面的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

1 个答案:

答案 0 :(得分: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();