繁体   English   中英

使用JAVA从XML文件读取数据

[英]reading data using JAVA from XML files

我知道关于这个问题有很多答案,但是在我看来,所有答案都没有用。 我将从此链接ECB读取欧洲中央银行的数据。 例如,如何读取其中time =“ 2015-02-27”的美元汇率,以及如何读取所有90天的美元汇率?

最简单的方法之一是使用DOM(文档对象模型)解析器。 它将把您的xml文档加载到内存中,并将其变成由Nodes组成的树,以便您可以遍历它,以获取任何位置的任何节点的信息。 它消耗内存,通常不如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();
   }
  }

}

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

货币:BGN汇率为1.9558

当前元素:立方体

货币:CZK汇率为27.797

当前元素:立方体

货币:DKK汇率为7.444

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM