Read data from xml at url in java

2019-09-18 16:42发布

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

标签: java xml url
2条回答
Deceive 欺骗
2楼-- · 2019-09-18 17:28

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();
        }
    }
}
查看更多
Deceive 欺骗
3楼-- · 2019-09-18 17:32

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.

查看更多
登录 后发表回答