Reading XML File
<?xml version="1.0" encoding="UTF-8"?> <persons> <person> <fn>Raj</fn> <ln>Mudwari</ln> </person> <person> <fn>Laurel</fn> <ln>Jonshan</ln> </person> </persons>
import java.awt.List;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
public class personxmlReader {
public static void main(String[] args) {
try {
File inputFile = new File("persons.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder;
dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse("persons.xml");
NodeList nodeList = doc.getElementsByTagName("person");
System.out.println("Number: "+nodeList.getLength());
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
{
if(node.getNodeType()==Node.ELEMENT_NODE) {
Element elem = (Element) node;
NodeList nl = elem.getChildNodes();
for(int j=0;j<nl.getLength();j++)
{
Node n = nl.item(j);
if(n.getNodeType()==Node.ELEMENT_NODE) {
Element el = (Element) n;
System.out.println(el.getTagName()+","+el.getTextContent());
}
}
}
}
}
}catch(Exception e) {
}
}
}