gpt4 book ai didi

c# - XmlDocument.Save OutOfMemory 异常

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

我一直在使用这个方便的功能来“美化”一个 xml 文档,以便使用缩进和换行符来格式化它。但是对于更大的文档(~1MB),出于某种原因,我在 doc.Save(writer) 处得到了 OutOfMemoryException。我该如何解决这个问题?

public static string BeautifyXmlDocument(XmlDocument doc)
{
MemoryStream sb = new MemoryStream();
XmlWriterSettings s = new XmlWriterSettings();
s.Indent = true;
s.IndentChars = " ";
s.NewLineChars = "\r\n";
s.NewLineHandling = NewLineHandling.Replace;
s.Encoding = new UTF8Encoding(false);
XmlWriter writer = XmlWriter.Create(sb, s);
doc.Save(writer);
writer.Close();
return Encoding.UTF8.GetString(sb.ToArray());
}

堆栈跟踪:

at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Xml.XmlUtf8RawTextWriter.FlushBuffer()
at System.Xml.XmlUtf8RawTextWriter.RawText(Char* pSrcBegin, Char* pSrcEnd)
at System.Xml.XmlUtf8RawTextWriter.RawText(String s)
at System.Xml.XmlUtf8RawTextWriter.WriteFullEndElement(String prefix, String localName, String ns)
at System.Xml.XmlUtf8RawTextWriterIndent.WriteFullEndElement(String prefix, String localName, String ns)
at System.Xml.XmlWellFormedWriter.WriteFullEndElement()
at System.Xml.XmlElement.WriteTo(XmlWriter w)
at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
at System.Xml.XmlElement.WriteTo(XmlWriter w)
at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
at System.Xml.XmlElement.WriteTo(XmlWriter w)
at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
at System.Xml.XmlElement.WriteTo(XmlWriter w)
at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
at System.Xml.XmlElement.WriteTo(XmlWriter w)
at System.Xml.XmlElement.WriteContentTo(XmlWriter w)
at System.Xml.XmlElement.WriteTo(XmlWriter w)
at System.Xml.XmlDocument.Save(XmlWriter w)

最佳答案

也许尝试在关闭流之前返回您的字符串,“using”语句在这里可以提供帮助。这似乎适用于 5MB 的 xml 文件。

  public static string BeautifyXmlDocument(XmlDocument doc)
{
using (MemoryStream sb = new MemoryStream())
{
XmlWriterSettings s = new XmlWriterSettings();
s.Indent = true;
s.IndentChars = " ";
s.NewLineChars = "\r\n";
s.NewLineHandling = NewLineHandling.Replace;
s.Encoding = new UTF8Encoding(false);
using (XmlWriter writer = XmlWriter.Create(sb, s))
{
doc.Save(writer);
return Encoding.UTF8.GetString(sb.ToArray());
}
}
}

关于c# - XmlDocument.Save OutOfMemory 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13545974/

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