如何格式化 Xml-Stream 以写入文件 [英] How to format a Xml-Stream for writing into file

查看:40
本文介绍了如何格式化 Xml-Stream 以写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从网络服务请求一个非常大的 (>500mb) xml 文件,并将 ResponseStream 的内容直接写入 FileStream.但是当我打开生成的 xml 文件时,内容如下所示:

I request a very large (>500mb) xml file from a web-service and write the contents of the ResponseStream directly into a FileStream. But when i open the resulting xml-file the contents look like this:

<Changes requestChangeTrackingId="-1" resultChangeTrackingId="2387">
<Selectors>
<Selector selectorId="1"><DateValidFrom>2000-01-01T00:00:00</DateValidFrom><DateValidTo>2099-12-31T00:00:00</DateValidTo><Code20Z>01A</Code20Z><CodeNUM/><CodeENT>1</CodeENT><ShortName>01A</ShortName></Selector>
<Selector selectorId="2"><DateValidFrom>2000-01-01T00:00:00</DateValidFrom><DateValidTo>2099-12-31T00:00:00</DateValidTo><Code20Z>01B</Code20Z><CodeNUM/><CodeENT>2</CodeENT><ShortName>01B</ShortName></Selector>

如何格式化流,使其看起来像这样:

How can i format the stream so that it will look like this:

<Changes requestChangeTrackingId="-1" resultChangeTrackingId="2387">
<Selectors>
<Selector selectorId="1">
   <DateValidFrom>2000-01-01T00:00:00</DateValidFrom>
   <DateValidTo>2099-12-31T00:00:00</DateValidTo>
   <Code20Z>01A</Code20Z>
   <CodeNUM/>
   <CodeENT>1</CodeENT>
   <ShortName>01A</ShortName>
</Selector>
[...]

我无法将整个文件加载到内存中,因此无法使用像

I cannot load the whole file into memory and therefore can't use a solution like

XDocument.Load( responseStream ).Save( "somefile.xml" );

有没有办法将流传递到某种 XmlStreamFormatter 并将流直接写入文件系统?要存储的文件可能很大,以至于不可能总是将整个流加载到内存中并在那里对其进行格式化.

Is there a way to pass a stream into some kind of XmlStreamFormatter and write the stream directly into the filesystem? The files to store can be so big that its not possible to always load the whole stream into memory and format it there.

推荐答案

XmlWriterSettings.Indent 在这里提供了一个机制的核心,所以它需要确保不需要加载整个内容(但是对运行的性能计数器进行一些仔细的测试是绝对可取.只有一个太急于读取数据的组件可能会导致大的地址空间和提交使用.因此,对于 500MB 数量级的数据大小,我将确保它仅针对 x64 构建 - 不构建 AnyCPU.

XmlWriterSettings.Indent provides the core of a mechanism here, so it a matter of ensuring that the whole content does not need to be loaded (but some careful testing with performance counters running is definitely advisable. Just one component too eager to read data in could lead to large address space and commit usage. Therefore with data sizes of the order of 500MB I would ensure this is built for x64 only—no AnyCPU builds.

比如:

void FormatXmlToFile(FileStream input, string outputFile) {
    using (var output = new FileStream(outputFile, FileMode.CreateNew)) {
        var reader = XmlReader.Create(input);
        var writerSettings = new XmlWriterSettings {
            Indent = true
        };

        using (var writer = XmlWriter.Create(output, writerSettings)) {
            writer.WriteNode(reader, true);
        }
    }
}

这篇关于如何格式化 Xml-Stream 以写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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