java - 阅读大型 xml 文档的最佳解决方案是什么?

标签 java xml

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/

相关文章:

java - XML 包装器 JSON 格式问题

java - 如何在eclipse中生成构造函数

java - 避免在控制逻辑中使用 isPresent() 和 get()

java - 如何从 Activity 的 fragment 返回到 viewpager 中的 fragment

android - 如何更改使用 java 代码中的 setBackgroundResource() 的 ImageView 的背景颜色?

java - 我可以在不编译的情况下获得 C/C++/Java 代码的 XML AST 吗?

java.util.NoSuchElementException(运行时错误)

java - .equals() 创建类构造函数并比较简单字符串

xml - Scala - 如何提取通用文本文件中包含的 XML 文件

javascript - 有没有办法让浏览器忽略或覆盖 xml-stylesheet 处理指令?