简体   繁体   中英

reading data using JAVA from XML files

I know there was a lot of answers about this question but all didn't work in my case. I would read data from European Central Bank from this link ECB . For example, how to read "rate" of USD where time="2015-02-27" and how to read "rate" of USD from all 90 days ?

One of the simplest ways to do it is to use a DOM (Document Object Model) parser. It will load your xml document in memory and turns it into a tree made of Nodes so that you can travers it being able to get the information of any node at any position. It is memory consumming and is generally less prefered than a SAX parser.

Here is an example:

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();
   }
  }

}

Applied to your file produces the following result:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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