簡體   English   中英

Java-讀取xml文件

[英]Java - read xml file

在Java中,我使用DocumentBuilderFactory,DocumentBuilder和Document讀取xml文件。 但是,現在我想制作一個方法,該方法返回遵循給定節點序列的所有值的數組列表。 為了更好地解釋,我將舉一個例子:說我有以下xml文件:

<one>
  <two>
    <three>5</three>
    <four>6</four>
  </two>
  <two>
    <three>7</three>
    <four>8</four>
  </two>
</one>

我使用帶有字符串參數“ one.two.three”的方法,現在返回值應該是包含數字5和7的數組。

我如何建立這個數組列表?

您可以使用xpath,盡管語法與點稍有不同(使用斜杠)

    Document d = ....

    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/one/two/three/text()"); // your example expression
    NodeList nl = (NodeList) expr.evaluate(d, XPathConstants.NODESET);
    for (int i = 0; i < nl.getLength(); i++) {
        String n = nl.item(i).getTextContent();
        System.out.println(n); //now do something with the text, like add them to a list or process them directly
    }

您可以在此處找到有關如何使用xpath查詢節點的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM