views:

99

answers:

2

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).

+4  A: 

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);
Marc Gravell
+1  A: 

Isn't that exactly what CDATA is meant to be used for in XML? All you need to watch out for is that your data doesn't contain "]]>", or that you escape them somehow using the time-honored C technique:

Encoding:
    '\' becomes '\\'
    ']' becomes '\]'
Decoding:
    '\]' becomes ']'
    '\\' becomes '\'
paxdiablo