Reputation: 3018
I have found examples how to stream whole documents but is there a way to stream node by node so I don't get a memory problem if the file is too big?
private Document document;
private void stream(OutputStream out) {
// write the doc into stream
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer;
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(out);
try {
transformer = transformerFactory.newTransformer();
transformer.transform(source, result);
} catch (TransformerException e) {
throw new RuntimeException("couldn't stream result to output");
}
}
Upvotes: 2
Views: 784
Reputation: 2532
Well you can always use recursion to travers through a Documents nodes if that can help you:
Element rootElement = document.getDocumentElement();
goThroughAllNodesOneByOne(rootElement);
goThroughAllNodesOneByOne(Node currentNode){
// Do your logic with the node
// EX: currentNode.getNodeName(); currentNode.getNamespaceURI() etc
NodeList childNodes = currentNode.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
goThroughAllNodesOneByOne(currentNode);
}
}
}
Upvotes: 0
Reputation: 3691
You could use the new StAX (Streaming API for XML) API to complete your task and read in chunks of XML.
The Oracle Documentation provides examples and I bet you will find other resources on-line too.
Upvotes: 1