954,193 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Eliminating Whitespace characters while parsing XML Files using DOM

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 :

<demo>
    <empid>e100</empid> 
     </demo>



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 inLINEAR fashion means i'm getting correct output .

LINEAR FASHION XML FILE:

<demo><empid>e100</empid></demo>



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

Thanks

parthiban
Junior Poster in Training
80 posts since Sep 2006
Reputation Points: 10
Solved Threads: 6
 

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.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You