poorvank
poorvank

Reputation: 7612

Parse a XML file in JAVA only once

I am learning parsing of an XML document in JAVA. But the problem i am facing is that the XML document is too large and i don't want my program to parse the document every time i need to find a particular childnode.

 DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
 DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
 doc = dBuilder.parse(file); 

How should i initialize my doc variable so that it parses my XML file only once!? Is it possible to use static here?

Upvotes: 0

Views: 441

Answers (3)

Michael Kay
Michael Kay

Reputation: 163585

Using static sounds a pretty bad idea in general: this means your large document will be locked in memory for the duration of the JVM. If you want to use the document repeatedly that suggests you're probably in some kind of long-running server, and you don't want to close down the server if, for example, the document is updated.

A much better solution is to maintain some kind of cache in which the document is held in instance data, eligible for garbage collection. How you do that depends on what kind of Java framework you are using.

Incidentally, do you really have to use DOM? It's slow, big, and ugly. There are much nicer tree models of XML available in the Java world, for example JDOM and XOM. (For that matter, do you have to use Java? There are much better languages for processing XML, such as XSLT and XQuery).

Upvotes: 0

Guy Bouallet
Guy Bouallet

Reputation: 2125

You can use a static field so that the doc can be shared after initialization between different threads/instances.

Note that DOM uses extra memory for document manipulation. You would probably prefer a SAX parser with POJO objects representing your XML data.

For performance and testability, you should also consider using a singleton with lazy initialization or a cache of objects.

Upvotes: 0

Tim B
Tim B

Reputation: 41208

There are a number of ways to do this, static would certainly be one option:

static final Document doc;

static {
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   doc = dBuilder.parse(file); 
}

This code defines a static final variable to hold the document, and then uses a static initializer block to actually set it up. Put this inside any class and it will create and initialize the doc variable for you.

Upvotes: 1

Related Questions