我有以下问题:
我有一个 XML 文件(大约 1GB),必须上下迭代(即不连续;一个接一个)以获得所需的数据并对其进行一些操作。最初,我使用 DOM Java 包,但很明显,在解析 XML 文件时,JVM 达到了其最大堆空间并停止了。
为了克服这个问题,我想到的解决方案之一是找到另一个解析器来迭代 XML 中的每个元素,然后将其内容存储在硬盘上的临时 SQLite 数据库中。因此,通过这种方式,JVM 的堆不会被超出,当所有数据都被填满后,我将忽略 XML 文件并继续对临时 SQLite 数据库进行操作。
还有其他方法可以解决我手头的问题吗?
最佳答案
SAX (Simple API for 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.helpers.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 {
}
}
关于java - 在 JAVA 中解析大型 XML 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15132390/