1

Avoid large objects in memory, or using String to hold large documents which should be handled with better tools. For example, don't read a large XML document into a String, or DOM.

The above quote is from an article. What is the best solution for reading a large xml document?

morgano
  • 17,210
  • 10
  • 45
  • 56
jiafu
  • 6,338
  • 12
  • 49
  • 73
  • SAX Parsing will solve your problem. try to read below link [http://stackoverflow.com/questions/3825206/why-is-sax-parsing-faster-than-dom-parsing-and-how-does-stax-work][1] – Amit Kathpal Apr 30 '14 at 05:44

2 Answers2

5

use SAX or StAX parser it will not hold all contents of xml in memory.

Unlike the DOM parser, the SAX parser does not create an in-memory representation of the XML document and so is faster and uses less memory. Instead, the SAX parser informs clients of the XML document structure by invoking callbacks, that is, by invoking methods on a org.xml.sax.helpes.DefaultHandler instance provided to the parser.

Here is an example implementation:

SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
DefaultHandler handler = new MyHandler();
parser.parse("file.xml", handler);

Where in

MyHandler

you define the actions to be taken when events like start/end of document/element are generated.(below is just elementary implementation)

class MyHandler extends DefaultHandler {

    @Override
    public void startDocument() throws SAXException {
    }

    @Override
    public void endDocument() throws SAXException {
    }

    @Override
    public void startElement(String uri, String localName, String qName,
            Attributes attributes) throws SAXException {
    }

    @Override
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
    }

    // To take specific actions for each chunk of character data (such as
    // adding the data to a node or buffer, or printing it to a file).
    @Override
    public void characters(char ch[], int start, int length)
            throws SAXException {
    }

}

this is good article for samples of SAX and StAX parser

niiraj874u
  • 2,180
  • 1
  • 12
  • 19
0

use SAX or Stax parser. don't go with DOM or JAXB.

Naveen Ramawat
  • 1,425
  • 1
  • 15
  • 27