What is the best way to serialize an arbitary string (into an XML attribute or XML node) to a XML stream so that the XML stays valid (special characters, newlines etc. must be encoded somehow).
2 Answers
I would simply use either a DOM (such as XmlDocument or XDocument), or for huge files, XmlWriter:
XDocument xdoc = new XDocument(new XElement("xml", "a < b & c"));
Console.WriteLine(xdoc.ToString());
XmlDocument xmldoc = new XmlDocument();
XmlElement root = xmldoc.CreateElement("xml");
xmldoc.AppendChild(root).InnerText = "a < b & c";
Console.WriteLine(xmldoc.OuterXml);
StringBuilder sb = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
using (XmlWriter xw = XmlWriter.Create(sb, settings))
{
xw.WriteElementString("xml", "a < b & c");
}
Console.WriteLine(sb);