using System;
using System.IO;
using System.Text;
using System.Xml;
class Test
{
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
XmlElement element = doc.CreateElement("child");
root.AppendChild(element);
doc.AppendChild(root);
MemoryStream ms = new MemoryStream();
doc.Save(ms);
byte[] bytes = ms.ToArray();
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
}
For more control over the formatting, you can create an XmlWriter from the stream and use XmlDocument.WriteTo(writer).
Try the following:
If you want to preserve the text encoding of the document, then change the
Default
encoding to the desired encoding, or follow Jon Skeet's suggestion.Steve Guidi: Thanks! Your code was right on the money! Here's how I solved my special characters issue:
Write it to a
MemoryStream
and then callToArray
on the stream:For more control over the formatting, you can create an
XmlWriter
from the stream and useXmlDocument.WriteTo(writer)
.