使用stax和dom读取一个大的XML文件 [英] Reading a big XML file using stax and dom

查看:110
本文介绍了使用stax和dom读取一个大的XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要阅读几个大型(200Mb-500Mb)的XML文件,所以我想使用StaX。
我的系统有两个模块 - 一个读取文件(使用StaX);另一个模块('parser'模块)假定要获得该XML的单个条目并使用DOM进行解析。
我的XML文件没有一定的结构 - 所以我不能使用JaxB。
我如何将解析器模块传递给我要解析的特定条目?
例如:

I need to read several big (200Mb-500Mb) XML files, so I want to use StaX. My system has two modules - one to read the file ( with StaX ); another module ( 'parser' module ) suppose to get a single entry of that XML and parse it using DOM. My XML files don't have a certain structure - so I cannot use JaxB. How can I pass the 'parser' module a specific entry that I want it to parse? For example:

<Items>
   <Item>
        <name> .... </name>
        <price> ... </price>
   </Item>
   <Item>
        <name> .... </name>
        <price> ... </price>
   </Item>
</Items>

我想使用StaX来解析该文件 - 但是每个item条目将被传递给'解析器'模块。

I want to use StaX to parse that file - but each 'item' entry will be passed to the 'parser' module.

编辑:

经过一点点阅读 - 我想我需要一个使用流读取XML文件的库 - 但是使用DOM解析每个条目。有没有这样的东西?


After a little more reading - I think I need a library that reads an XML file using stream - but parse each entry using DOM. Is there such a thing?

推荐答案

你可以使用StAX( javax.xml.stream )解析器和转换( javax.xml.transform )每个部分到DOM节点( org.w3c.dom ):

You could use a StAX (javax.xml.stream) parser and transform (javax.xml.transform) each section to a DOM node (org.w3c.dom):

import java.io.*;
import javax.xml.stream.*;
import javax.xml.transform.*;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.dom.DOMResult;
import org.w3c.dom.*

public class Demo {

    public static void main(String[] args) throws Exception  {
        XMLInputFactory xif = XMLInputFactory.newInstance();
        XMLStreamReader xsr = xif.createXMLStreamReader(new FileReader("input.xml"));
        xsr.nextTag(); // Advance to statements element

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        while(xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
            DOMResult result = new DOMResult();
            t.transform(new StAXSource(xsr), result);
            Node domNode = result.getNode();
        }
    }

}

另见:

  • Split 1GB Xml file using Java

这篇关于使用stax和dom读取一个大的XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆