Reputation: 99
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
Upvotes: 0
Views: 946
Reputation: 31
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();
}
}
}
Upvotes: 0
Reputation: 31
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.
Upvotes: 1