gpt4 book ai didi

c# - 重用 XmlTextWriter 类

转载 作者:数据小太阳 更新时间:2023-10-29 02:32:22 25 4
gpt4 key购买 nike

是否可以重用 XmlTextWriter 类的同一个实例来生成更多的 xml 文档?我的意思是这样的:

XmlTextWriter writer = new XmlTextWriter();
writer.WriteStartDocument();
writer.WriteStartElement("Message1");
writer.WriteEndElement();
writer.WriteEndDocument();

// do something with xml created
...

writer.Reset() // ?
writer.WriteStartDocument();
writer.WriteStartElement("Message2");
writer.WriteEndElement();
writer.WriteEndDocument();
// do something with xml created
...

最佳答案

简单的回答:是的,这是可能的。

但如果底层流不指向文件,这将实现。 MemoryStream 就是一个很好的例子。

由于 MemoryStream 将流保存在“内存中”,您可以使用 XmlTextWriter 编写大量 XML 文件,并在结束每个文档后执行 MemoryStream.ToArray() 并将其作为 File.WriteAllBytes 的参数。

写入所有字节后,您将清除内存流。

您可以通过调用 MemoryStream.SetLength 方法清除内存流,并将长度设为 0:

在此处阅读更多有关 XmlTextWriter 构造函数的流重载的信息:

这对于 File.WriteAllBytes:

关于重用XmlTextWriter

的一些问题

几年前@NigelTouch 对一些评论提出了担忧:

The problem I found is that if an exception is thrown part-way through, for example after WriteStartElement(), then even though you Flush() the Writer and set the Stream length to 0, the Writer remains in a WriteState of Element. When you start the next document, it begins with a closing ">" (for example). Avoid reuse

几个小时前,@Mike-EEE 遇到了同样的问题:

Please provide working code of an example solution. I am running into the same problem as Nigel describes

顺便说一句,一些试错让我恢复了给定的 XmlTextWriter 以根据需要多次重复使用它:

    using(MemoryStream stream = new MemoryStream())
using(StreamReader streamReader = new StreamReader(stream))
using(XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
{
writer.WriteStartDocument(true);
writer.WriteStartElement("a");

try
{
throw new Exception();
}
catch
{
// This line makes de magic: ending the document
// avoids the issue mentioned by @NigelTouch
writer.WriteEndDocument();
writer.Flush();
stream.SetLength(0);
}


writer.WriteStartDocument(true);
writer.WriteStartElement("b");
writer.WriteEndElement();
writer.Flush();

stream.Position = 0;

Console.WriteLine(streamReader.ReadToEnd());

}

关于c# - 重用 XmlTextWriter 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4919210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com