如果您接受 JAXB/Spring Batch 之外的解决方案,您可能想看看 SAX Parser。
这是一种更加面向事件的解析 XML 文件的方式,当您希望在解析时直接写入目标文件时,这可能是一种好方法。SAX 解析器不会将整个 xml 内容读入内存,而是在输入流中遇到元素时触发方法。据我体验,这是一种非常节省内存的处理方式。
与您的 Stax-Solution 相比,SAX 将数据“推送”到您的应用程序中——这意味着您必须维护状态(例如您当前所在的标签),因此您必须跟踪您当前的位置。我不确定这是否是您真正需要的
以下示例读取结构中的 xml 文件并打印出 GroupBMsg-Tags 中的所有文本:
import java.io.FileReader;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
public class SaxExample implements ContentHandler
{
private String currentValue;
public static void main(final String[] args) throws Exception
{
final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
final FileReader reader = new FileReader("datasource.xml");
final InputSource inputSource = new InputSource(reader);
xmlReader.setContentHandler(new SaxExample());
xmlReader.parse(inputSource);
}
@Override
public void characters(final char[] ch, final int start, final int length) throws SAXException
{
currentValue = new String(ch, start, length);
}
@Override
public void startElement(final String uri, final String localName, final String qName, final Attributes atts) throws SAXException
{
// react on the beginning of tag "GroupBMsg" <GroupBMSg>
if (localName.equals("GroupBMsg"))
{
currentValue="";
}
}
@Override
public void endElement(final String uri, final String localName, final String qName) throws SAXException
{
// react on the ending of tag "GroupBMsg" </GroupBMSg>
if (localName.equals("GroupBMsg"))
{
// TODO: write into file
System.out.println(currentValue);
}
}
// the rest is boilerplate code for sax
@Override
public void endDocument() throws SAXException {}
@Override
public void endPrefixMapping(final String prefix) throws SAXException {}
@Override
public void ignorableWhitespace(final char[] ch, final int start, final int length)
throws SAXException {}
@Override
public void processingInstruction(final String target, final String data)
throws SAXException {}
@Override
public void setDocumentLocator(final Locator locator) { }
@Override
public void skippedEntity(final String name) throws SAXException {}
@Override
public void startDocument() throws SAXException {}
@Override
public void startPrefixMapping(final String prefix, final String uri)
throws SAXException {}
}