Java HTML / XML How to - Read data from xml at url








Question

We would like to know how to read data from xml at url.

Answer

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/*from   w w w. jav  a2  s  .co m*/
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) throws Exception {
    InputStream is = new URL("http://www.your server.com/daily.xml")
        .openStream();
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(is);
    NodeList nodeList = doc.getElementsByTagName("v");
    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(element.getAttribute("rate"));
        }
      }
    }
  }
}