gpt4 book ai didi

c# - XElement.ToString() 导致 System.OutOfMemoryException

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

我有一个包含大约 120MB 数据的 XElement 对象。 XML 由大约 6000 个元素组成,每个元素约 20kb。

我正在尝试调用 XElement.ToString(),因为我需要在网络服务中返回 OuterXml。

我得到一个 System.OutOfMemoryException

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
at System.Text.StringBuilder.GetNewString(String currentString, Int32 requiredLength)
at System.Text.StringBuilder.Append(Char[] value, Int32 startIndex, Int32 charCount)
at System.IO.StringWriter.Write(Char[] buffer, Int32 index, Int32 count)
at System.Xml.XmlEncodedRawTextWriter.FlushBuffer()
at System.Xml.XmlEncodedRawTextWriter.WriteAttributeTextBlock(Char* pSrc, Char* pSrcEnd)
at System.Xml.XmlEncodedRawTextWriter.WriteString(String text)
at System.Xml.XmlEncodedRawTextWriterIndent.WriteString(String text)
at System.Xml.XmlWellFormedWriter.WriteString(String text)
at System.Xml.XmlWriter.WriteAttributeString(String prefix, String localName, String ns, String value)
at System.Xml.Linq.ElementWriter.WriteStartElement(XElement e)
at System.Xml.Linq.ElementWriter.WriteElement(XElement e)
at System.Xml.Linq.XElement.WriteTo(XmlWriter writer)
at System.Xml.Linq.XNode.GetXmlString(SaveOptions o)
at System.Xml.Linq.XNode.ToString()

我在 XmlDocument 中有相同的数据,可以毫无问题地调用 XmlDocument.OuterXml。我还可以调用 XElement.Save() 将 XML 毫无问题地保存到文件中。

谁能建议 XElement.ToString() 的内存占用较少的替代方法?或者我可以设置一些参数以允许更大的内存空间?

最佳答案

听起来你在那里写的数据方式太多了; 通常原始XmlWriter 可能是本卷的最佳选择。但是,如果您可以 Save() 成功,您或许可以尝试:

    string xml;
using(var sw = new StringWriter()) {
el.Save(sw);
xml = sw.ToString();
}

或者也许:

    string xml;
using (var ms = new MemoryStream()) {
using(var tw = new StreamWriter(ms, Encoding.UTF8))
{
el.Save(tw);
}
xml = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length);
}

但其中任何一个(或两者)都可能会在一阵 Spark 中爆炸。您可能还想调查 XStreamingElement这是为这种情况设计的...但是,这仍然是很多 xml - 特别是对于网络服务。您愿意接受其他(更密集的)序列化格式的建议吗?

关于c# - XElement.ToString() 导致 System.OutOfMemoryException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4275506/

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