XMLParsingBCE.java

Java source code icon XMLParsingBCE.java — Java source code, 1 kB (1997 bytes)

Continguts del fitxer

import java.net.URL;

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;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

public class XMLParsingBCE extends Activity {
	public static final String TAG = "XMLParsingECB";
	
	public void log(String s) {
		Log.d(TAG, s);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/** Create a new layout to display the view */
		LinearLayout layout = new LinearLayout(this);
		layout.setOrientation(LinearLayout.VERTICAL);

		try {

			URL url = new URL(
					"http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");
			
			log("URL: " + url);
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(new InputSource(url.openStream()));
			doc.getDocumentElement().normalize();

			NodeList nodeList = doc.getElementsByTagName("Cube");
			log("nodeList.getlength(): " + nodeList.getLength());
			for(int i=0; i<nodeList.getLength(); i++) {
				Node node = nodeList.item(i);
				
				log("i=" + i + " node: " + node);
				
				if(node instanceof Element) {
					log("es un Element");
				} else {
					log("no es un Element");
				}
				
				Element element = (Element)node;
				
				String currency = element.getAttribute("currency");
				String rate = element.getAttribute("rate");
				
				log("currency=" + currency + " rate=" + rate);
				
				TextView tv = new TextView(this);
				tv.setText("currency=" + currency + " rate=" + rate);
				layout.addView(tv);
				
			}

			
		} catch (Exception e) {
			log("XML Pasing Excpetion = " + e);
		}

		/** Set the layout view to display */
		setContentView(layout);

	}
}