Vamsi Pavan’s Place

When curiousity outbursts …..

Building DOM tree by reading an xml file in Java

December 19th, 2007 · No Comments · Java, Source Code

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

public class BasicDom {
public static void main(String[] args) {
Document doc = parseXmlFile(”infilename.xml”, false);
}

// Parses an XML file and returns a DOM document.
// If validating is true, the contents is validated against the DTD
// specified in the file.
public static Document parseXmlFile(String filename, boolean validating) {
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);

// Create the builder and parse the file
Document doc = factory.newDocumentBuilder().parse(new File(filename));
return doc;
} catch (SAXException e) {
// A parsing error occurred; the xml input is not valid
} catch (ParserConfigurationException e) {
} catch (IOException e) {
}
return null;
}
}

This is the common code used to parse XML files in Java. Often we see calling this method from other part of code as

Document doc = parseXmlFile(”infilename.xml”, false);

So, this become commonly used scripts in XML programming with Java.

Bookmark it! These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google
  • Live
  • StumbleUpon
  • BlinkList
  • YahooMyWeb
  • NewsVine
  • blogtercimlap
  • Netvouz
  • Technorati
  • Slashdot
  • Print this article!

Tags:

0 responses so far ↓

  • There are no comments yet...Kick things off by filling out the form below.

Leave a Comment