【发布时间】:2012-08-09 15:09:12
【问题描述】:
我需要编写一个工具来处理以下格式不正确的 XML 片段,因为它在流中间包含 XML 声明。
公司已长期使用此类文件,无法更改格式。
没有可用于解析的源代码,新工具的首选平台是 .NET 4 或更新版本,最好使用 C#。
片段如下所示:
<Header>
<Version>1</Version>
</Header>
<Entry><?xml version="1.0"?><Detail>...snip...</Detail></Entry>
<Entry><?xml version="1.0"?><Detail>...snip...</Detail></Entry>
<Entry><?xml version="1.0"?><Detail>...snip...</Detail></Entry>
<Entry><?xml version="1.0"?><Detail>...snip...</Detail></Entry>
使用XmlReader 并将XmlReaderSettings.ConformanceLevel 设置为ConformanceLevel.Fragment,我可以阅读完整的<Header> 元素。
即使<Entry> 元素开始也可以,但是在读取<Detail> 信息时,XmlReader 它会抛出一个XmlException,因为它在<?xml...?> XML 声明中读取它并不期望在那个地方。
除了繁重的字符串操作之外,我还有哪些选项可以跳过这些 XML 声明?
由于片段可以轻松超过 100 兆字节,我宁愿不要一次将所有内容加载到内存中。但这就是它所需要的,我愿意接受。
我得到的异常示例:
System.Xml.XmlException: Unexpected XML declaration.
The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it.
Line ##, position ##.
【问题讨论】:
-
您是否尝试过使用 System.Xml.Linq (msdn.microsoft.com/de-de/library/bb299195) 命名空间中的类?
-
还没有;哪些最适合从解析片段开始? LINQ 的内存消耗有多大?这些文件可以很容易地达到 100 兆字节。
标签: c# xml .net-4.0 xml-parsing xmlreader