cheedella_koti@yahoo.com hi,
i am facing a problem in parsing xml file in
java by using DOM parser.
my input xml file is:
<?xml version="1.0" ?>
<links>
<link1>
<name>abc</name>
<val>123</val>
</link1>
<link2>
<name>xyz</name>
<val>456</val>
</link2>
</links>
and java prog is:
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class xmlparse {
public static void main(
String[] args) throws Exception
{
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
DocumentBuilder dlb = fac.newDocumentBuilder();
System.out.println(dlb + " At creation");
Document
doc = dlb.parse(new File("c:\\xmlexp.xml"));
System.out.println(doc +" At Parsing");
Node root = doc.getDocumentElement();
System.out.println(root.getNodeName() + " Root element");
NodeList childs = root.getChildNodes();
System.out.println(childs.getLength()+" No of childs");
for (int i=0; i<childs.getLength();i++)
{
Node first = childs.item(i);
System.out.println(first.getNodeName() + " Node element");
Node firstchild = first.getFirstChild();
String firsttext = first.getFirstChild().getNodeValue();
System.out.println(firsttext +" firstchild value");
Node lastchild = first.getLastChild();
String lasttext = lastchild.getFirstChild().getNodeValue();
System.out.println(lasttext +" lastchild value");
}
}
}
and the output i got is:
org.apache.crimson.jaxp.DocumentBuilderImpl@fabe9 At creation
org.apache.crimson.tree.XmlDocument@1888759 At Parsing
links Root element
5 No of childs
#text Node element
java.lang.NullPointerException
at xmlparse.main(xmlparse.java:27)
Exception in
thread "main"
in my xml file the root tag (<links>) contains 2 child tags (<link1>,<link2>)
but the output of my java prog is showing 5 child tags. please tell me why my java prog is behaving like this and provide me the solution.