简体   繁体   中英

Stream XML node by node

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");
    }
}

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.

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);
        }
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM