如何在一个文档中解析多个连续的 xml 文件? [英] How to parse multiple, consecutive xml files in one document?

查看:23
本文介绍了如何在一个文档中解析多个连续的 xml 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大文本文件,它是一系列 XML 有效文档,看起来像这样:

I have a big text file that is a sequence of XML-valid documents that looks something like this:

<DOC>
   <TEXT> ... </TEXT>
    ...
</DOC>
<DOC>
    <TEXT> ... </TEXT>
    ...
</DOC>

等等.没有 分隔每个单独的 xml.在 Java 中解析它并获取每个 下的值的最佳方法是什么?

etc. There is no <?xml version="1.0">, the <DOC></DOC> delimits each separate xml. What's the best way to parse this in Java and get the values under <TEXT> in each <DOC>?

如果我将整个内容传递给 DocumentBuilder,我会收到错误消息,指出文档格式不正确.有没有比简单地遍历更好的解决方案,为每个 构建一个字符串?

If I pass the whole thing to a DocumentBuilder, I get an error saying the document is not well formed. Is there a better solution than simply traversing through, a building a string for each <DOC>?

推荐答案

valid XML 文档必须有一个 root 元素,您可以在该元素下指定所有其他元素.此外,在一个文档中只能存在一个 root 元素.看看 XML 规范(见第 2 点)

A valid XML document must have a root element under which you can specify all other elements. Also, in a document only ONE root element can be present. have a look on XML Specification (see point 2)

因此,为了解决您的问题,您可以将文本文件的所有内容放入一个字符串(或 StringBuffer/StringBuilder...)中,并将该字符串放在 <root> 标签例如,

So, to overcome your issue, you can take all the content of your text file into a String (or StringBuffer/StringBuilder...) And put this string in between <root> and </root> tags e.g ,

String origXML = readContentFromTextFile(fileName);
String validXML = "<root>" + origXML + "</root>";
//parse validXML

这篇关于如何在一个文档中解析多个连续的 xml 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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