Skip to content

Instantly share code, notes, and snippets.

@MartinP7r
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MartinP7r/8510abc44e99964e1f29 to your computer and use it in GitHub Desktop.
Save MartinP7r/8510abc44e99964e1f29 to your computer and use it in GitHub Desktop.
Parses ECB €-exchange rates feed into objects arraylist-list <EuroExchangeRate> "ratesList"
package exchangeRateApp;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.html.HTMLDocument.HTMLReader.IsindexAction;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ERParser {
public static void main(String[] args) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputStream input = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml").openStream();
Document document = builder.parse(input);
List<EuroExchangeRate> ratesList = new ArrayList<>();
NodeList nodeList = document.getDocumentElement().getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
if (nodeList.item(i).getNodeName() == "Cube") {
NodeList upperNodes = nodeList.item(i).getChildNodes();
for (int k = 0; k < upperNodes.getLength(); k++) {
Node upperNode = upperNodes.item(k);
if (upperNode instanceof Element) {
String updateTime = upperNode.getAttributes().getNamedItem("time").getNodeValue();
NodeList childNodes = upperNode.getChildNodes();
for (int j = 0; j < childNodes.getLength(); j++) {
Node node = childNodes.item(j);
if (node instanceof Element) {
EuroExchangeRate exRate = new EuroExchangeRate ();
exRate.time = updateTime;
exRate.currency = node.getAttributes().getNamedItem("currency").getNodeValue();
exRate.rate = node.getAttributes().getNamedItem("rate").getNodeValue();
ratesList.add(exRate);
}
}
}
}
}
}
// test output
//for (EuroExchangeRate exchangeRate : ratesList) {
// System.out.println(exchangeRate);
//}
}
}
package exchangeRateApp;
class EuroExchangeRate {
String time;
String currency;
String rate;
public String toString() {
return "EUR to "+currency+": "+rate+ " (date: "+time+")";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment