我找到了如何流式传输整个文档的示例,但有没有办法按节点流式传输,所以如果文件太大,我不会遇到内存问题?
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");
}
}
答案 0 :(得分:0)
您可以使用新的StAX(Streaming API for XML)API来完成任务并读取XML块。
Oracle Documentation提供了示例,我敢打赌,您也可以在线找到其他资源。
答案 1 :(得分:0)
您可以随时使用递归来遍历Documents节点,如果这可以帮助您:
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);
}
}
}