File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes XML and Related Technologies and the fly likes Regarding xml parsing using dom Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Regarding xml parsing using dom" Watch "Regarding xml parsing using dom" New topic

Regarding xml parsing using dom

koteswara rao cheedella

Joined: Mar 01, 2006
Posts: 1 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" ?>

and java prog is:

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
at xmlparse.main(
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.
Purushoth Thambu
Ranch Hand

Joined: May 24, 2003
Posts: 425
The actual DOM structure of your TOP element <links> is
Node (link1)
Node (link2)

See the Text element API to understand the DOM structure.
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
There is a VERY handy table in org.w3c.dom.Node JavaDocs that shows what every kind of Node responds with for the various methods.
There you will see that many types of Node have a nodeValue of null, including Element nodes.
I agree. Here's the link:
subject: Regarding xml parsing using dom
It's not a secret anymore!