使用 JAVA 从 XML 个文件中读取数据

reading data using JAVA from XML files

我知道有很多关于这个问题的答案,但都不适用于我的情况。我会从这个 link ECB 中读取欧洲中央银行的数据。例如,如何读取 "rate" of USD where time="2015-02-27" 以及如何读取所有 90 天的 "rate" of USD ?

最简单的方法之一是使用 DOM(文档对象模型)解析器。它会将你的 xml 文档加载到内存中,并将其变成一棵由节点组成的树,这样你就可以遍历它,从而能够在任何位置获取任何节点的信息。它很消耗内存,通常不如 SAX 解析器受欢迎。

这是一个例子:

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class DomParsing {

    public static final String ECB_DATAS ="C:\xml\eurofxref-hist-90d.xml"; 


    public static void main(String argv[]) {

    try {

        File fXmlFile = new File(ECB_DATAS);
        DocumentBuilderFactory dbFactory =     DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();

        System.out.println("Root element :" +         doc.getDocumentElement().getNodeName());

        NodeList nList = doc.getElementsByTagName("Cube");

        for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);

            System.out.println("\nCurrent Element :" + nNode.getNodeName());

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

                Element eElement = (Element) nNode;


                System.out.println("currency : " +   eElement.getAttribute("currency") + " and rate is " +   eElement.getAttribute("rate"));

        }
    }
   } catch (Exception e) {
     e.printStackTrace();
   }
  }

}

应用于您的文件会产生以下结果:

currency : BGN and rate is 1.9558

Current Element :Cube

currency : CZK and rate is 27.797

Current Element :Cube

currency : DKK and rate is 7.444