I have been using this handy function to "beautify" an xml document, so that it's formatted with indentations and newlines. But with bigger documents (~1MB), I get an OutOfMemoryException at doc.Save(writer) for some reason. How can I fix this issue?
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());
}
Stack trace:
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)
Maybe try returning your string before closing the stream, The "using" statement can help here. This seems to work fine for a 5MB xml file.
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());
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With