简体   繁体   中英

Read data from xml at url in java

I need to be able to pull out the USD conversion from Euro using this xml: http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

I've gotten it to work if I manually download the xml and parse to the data I need from there, but I'm not sure how to grab it directly from the url.

Thank you

If i understand well, you are having trouble obtaining the xml content directly from the URL, is that right?

If so, this might help you.

// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));

// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());

It applies well to a service or stand alone context, but if you are trying to access the XML from your WEB tier you might consider an AJAX approach.

Cant make any easier than that:

package com.danielmarreco;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;
import java.net.URL;

public class Main {

    public static void main(String[] args) {
        try {
            InputStream is = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml").openStream();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.parse(is);

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

            for (int i = 0; i < nodeList.getLength(); i ++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    if(element.getAttribute("currency").equals("BRL")) 
                        System.out.println("1 EUR = " + element.getAttribute("rate") + " BRL");
                }
            }
        }
        catch (Exception e)        {
            e.printStackTrace();
        }
    }
}

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