C# 如何将XElement写入已包含内容的XmlWriter
我正在尝试以流式方式编写一个非常大的XML文档。与其编写一个C# 如何将XElement写入已包含内容的XmlWriter,c#,xml,linq-to-xml,C#,Xml,Linq To Xml,我正在尝试以流式方式编写一个非常大的XML文档。与其编写一个XDocument或XElement(这可能会消耗太多内存),不如使用XmlWriter编写根元素,然后在关闭根元素之前,一个接一个地向该编写器写入多个XElement。然而,我还没有找到这样做的方法。为了模拟这个问题,考虑下面的代码: using System; using System.Xml; using System.Xml.Linq; internal static class Program { private s
XDocument
或XElement
(这可能会消耗太多内存),不如使用XmlWriter
编写根元素,然后在关闭根元素之前,一个接一个地向该编写器写入多个XElement。然而,我还没有找到这样做的方法。为了模拟这个问题,考虑下面的代码:
using System;
using System.Xml;
using System.Xml.Linq;
internal static class Program
{
private static void Main()
{
var settings = new XmlWriterSettings { Encoding = Console.OutputEncoding, Indent = true };
using (var writer = XmlWriter.Create(Console.Out, settings))
{
const string namespaceUri = "http://example.com/";
writer.WriteStartElement("x", "root", namespaceUri);
XNamespace x = namespaceUri;
XElement element = new XElement(x + "test");
element.Save(writer);
writer.WriteEndElement();
}
Console.WriteLine();
}
}
程序在元素Save(writer)上失败代码>行,带有InvalidOperationException
:“状态元素开始标记中的令牌StartDocument将导致无效的XML文档”
出现此异常的原因很清楚:XElement假定它自己拥有整个XmlWriter,并对其调用WriteStartDocument()
。显然,这是失败的,因为文档已经启动,并且其中已经有一个start元素
请注意,如果我使用XDocument
,我会预期这种行为,但我不是,我使用的是XElement
另一种选择是写作
writer.WriteRaw(element.ToString());
而不是
element.Save(writer);
它可以工作,因为它不会崩溃,而且可以生成正确的XML
但是,我不喜欢它,因为它不能生成我所寻找的干净高效的XML(它不必要地重复名称空间声明)。显然不能,因为XElement是在没有XmlWriter应该提供的上下文的情况下序列化的。事实上,它需要一个中介字符串来工作甚至不是最大的问题
如何以有效的方式将多个XElement
实例一个接一个地独立地写入XmlWriter
,从而生成干净的XML?或者这是不可能的?如果您更改元素。保存(writer)代码>到元素。写入到(写入器)代码>没有例外,它似乎写入了控制台。我怎么可能没有看到这个方法?无论如何,非常感谢!只是想与其他人分享,如果你碰巧有一个XDocument,你也可以访问Root属性来完成这项工作。幸好你没有看到这个方法。否则,您就不会发布此问题,我也不会发现此问题:)