0
votes

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

2
You could use the any of the solutions described here: stackoverflow.com/questions/8324862/… or here: weblogs.java.net/blog/kohsuke/archive/2007/04/…6ton
Check out the android-async-http library.Kevin Krumwiede
Thanks Chetan, I looked up that stackoverflow link you provided and FileUtils.copyURLToFile(url, f); was EXACTLY what I needed. Just threw it into a temporary file and I could parse it just fine. Thanks!firexion

2 Answers

1
votes

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.

0
votes

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