Så här kan du göra
import org.apache.crimson.jaxp.DocumentBuilderFactoryImpl;
import org.apache.xpath.XPathAPI;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class ParseXML3
{
public ParseXML3() throws Exception
{
//Få in xmlsträngen som ett dokument på ett eller annat sätt
Document mDocument = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder().parse("conf/ratelist.xml");
NodeList list = XPathAPI.selectNodeList(mDocument, "/RateList/Rate");
String date, unitName, country, inUsd, value;
for (int i = 0; i < list.getLength(); i++)
{
Node node = list.item(i);
date = XPathAPI.selectSingleNode(node, "Date").getFirstChild().toString();
unitName = XPathAPI.selectSingleNode(node, "Country/@UnitName").getNodeValue();
country = XPathAPI.selectSingleNode(node, "Country").getFirstChild().toString();
inUsd = XPathAPI.selectSingleNode(node, "Value/@InUsd").getNodeValue();
value = XPathAPI.selectSingleNode(node, "Value").getFirstChild().toString();
System.out.println("date " + date);
System.out.println("unitname " + unitName);
System.out.println("country " + country);
System.out.println("inusd " + inUsd);
System.out.println("value " + value);
}
}
public static void main(String[] args) throws Exception
{
new ParseXML3();
}
}
Här kan du läsa mer om XPath om hur det fungerar:
http://java.sun.com/webservices/docs/1.3/tutorial/doc/index.html
