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.
以上引用来自一篇文章。读取大型 xml 文档的最佳解决方案是什么?
最佳答案
使用 SAX 或 StAX 解析器它不会在内存中保存 xml 的所有内容。
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.
这是一个示例实现:
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
DefaultHandler handler = new MyHandler();
parser.parse("file.xml", handler);
在哪里
MyHandler
您定义在生成文档/元素的开始/结束等事件时要采取的操作。(以下只是基本实现)
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是 SAX 和 StAX 解析器示例的好文章
关于java - 阅读大型 xml 文档的最佳解决方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23380420/