Friday, May 21, 2010

Java XML Simple Read Example

To Read and extract the elements from the XML file first parse the XML file though the parser and create the Document
Document doc = builder.parse(str);

Once the document is availabe we can fetch the root and elements as follows
Node node = doc.getDocumentElement();
String root = node.getNodeName();

Example is given below

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.*;

public class GetRootNode{
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter xml file name: ");
String str = bf.readLine();
File file = new File(str);
if (file.exists()){
DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = fact.newDocumentBuilder();
Document doc = builder.parse(str);
Node node = doc.getDocumentElement();
String root = node.getNodeName();
System.out.println("Root Node: " + root);
}
else{
System.out.println("File not found!");
}
}
catch(Exception e){}
}
}

1 comment:

  1. Hi nice post about XML. I suggest a more descriptive edition. Check for more @ StarkSolutions

    ReplyDelete