This example will get you started in the exciting world of XML parsing with Java and DOM!
Test.xml
<root>
<foo>someFoo</foo>
<child>
<subchild name="chris">valueOne</subchild>
</child>
<child>
<subchild name="barry">valueTwo</subchild>
</child>
</root>
XMLParsingExample.java
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
public class XMLParsingExample {
public static void main(String [] args) {
System.out.println("Starting...");
try {
String fileName = "test.xml";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
// Could use an InputStream instead of a File
Document xmlDocument = builder.parse(new File(fileName));
Element rootNode = xmlDocument.getDocumentElement();
NodeList nodeList = rootNode.getElementsByTagName("child");
for(int i=0;i < nodeList.getLength();i++) {
Node node = nodeList.item(i);
System.out.println(node);
}
}
catch(Exception e) { e.printStackTrace(); }
}
}