0

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 in LINEAR 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

2
Contributors
1
Reply
2
Views
10 Years
Discussion Span
Last Post by jwenting
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.