在java中流式传输xml
我正在尝试读取大型 XML 文件,我只想读取车主,但无法将整个 xml 加载到内存中,该怎么做?
XML 文件:
<root>
<message>
<car>
<owner>adam</owner>
</car>
<desk>
<owner>sam</owner>
<game>
<owner>dorothy</owner>
</game>
<pen>
<owner>dorothy</owner>
</pen>
</desk>
</message>
</root>
例如,这段代码并不确切知道它读取的内容。如何确保我们正在读取车主信息?
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLEventReader reader = xmlInputFactory.createXMLEventReader(new FileInputStream(entry.toFile()));
while (reader.hasNext()) {
XMLEvent nextEvent = reader.nextEvent();
if (nextEvent.isStartElement()) {
StartElement startElement = nextEvent.asStartElement();
log.info(startElement.getName().toString());
switch (startElement.getName().getLocalPart()) {
case "owner":
// whose owner. .. ?
I am trying to read large XML file, I want only to read cars owners and I can't load whole xml to memory, how to do that ?
The XML file:
<root>
<message>
<car>
<owner>adam</owner>
</car>
<desk>
<owner>sam</owner>
<game>
<owner>dorothy</owner>
</game>
<pen>
<owner>dorothy</owner>
</pen>
</desk>
</message>
</root>
For example this code does not know exactly what it reads.. how to be sure that we are reading car owners ?
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
XMLEventReader reader = xmlInputFactory.createXMLEventReader(new FileInputStream(entry.toFile()));
while (reader.hasNext()) {
XMLEvent nextEvent = reader.nextEvent();
if (nextEvent.isStartElement()) {
StartElement startElement = nextEvent.asStartElement();
log.info(startElement.getName().toString());
switch (startElement.getName().getLocalPart()) {
case "owner":
// whose owner. .. ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
坚固但可行的解决方案是创建一个小型状态机,捕获事件并相应地改变状态
Sturdy but viable solution is to create a small state machine, capture events as they go and mutate state accordingly