Hi all ,

I'm having problem during parsing xml files using DOM API due to whitespace characters.

Here is my sample XML File ,coding and output :

XML File :


Coding :

import java.io.*;
import org.w3c.dom.*;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;

class demo{
    public static void main(String args[]) throws IOException {
        try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File("C:/Documents and Settings/t48ezi/Desktop/demo.xml"));
        Element rootElement = doc.getDocumentElement();
        System.out.println("root ==> "+rootElement.getNodeName());
        NodeList sublist = rootElement.getChildNodes();
        System.out.println("sublistlength --> "+sublist.getLength());
        System.out.println("sub name 0 :: "+sublist.item(0).getNodeName());
        System.out.println("sub name 1 :: "+sublist.item(1).getNodeName());
        System.out.println("sub name 2 :: "+sublist.item(2).getNodeName());
        catch(Exception e){}

Output :

root ==> demo
sublistlength --> 3
sub name 0 :: #text
sub name 1 :: empid
sub name 2 :: #text

I have only one chid but i got the number of child of rootelement as "3" due to whitespace character as shown in output(#text) but when i manually type XML Files in LINEAR fashion means i'm getting correct output .



but i used a code that automatically generate xml format . So , how to eliminate that (#text) ?


You don't. You rather learn to use the XML parser properly and explicitly read only those elements from the tree that you actually need.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.