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