DOM PARSER (Simplest Code Ever)
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class MyDomParser {
public static void main(String args[]) throws SAXException, IOException
{
DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("people.xml");
NodeList personlist=doc.getElementsByTagName("person");
for(int i=0;i<personlist.getLength();i++)
{
Node p=personlist.item(i);
if(p.getNodeType()==Node.ELEMENT_NODE)
{
Element person=(Element) p;
String id=person.getAttribute("id");
NodeList namelist=person.getChildNodes();
for(int j=0;j<namelist.getLength();j++)
{
Node n=namelist.item(j);
if(n.getNodeType()==Node.ELEMENT_NODE)
{
Element name=(Element) n;
System.out.println("person"+id+":"+name.getTagName()+"="+name.getTextContent());
}
}
}
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
XML File (people.xml)
<?xml version="1.0"?>
<people>
<person id="1">
<lastname>pawar</lastname>
<firstname>ashutosh</firstname>
</person>
<person id="2">
<lastname>khedkar</lastname>
<firstname>amol</firstname>
</person>
</people>
No comments:
Post a Comment