簡體   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