Saturday, April 30, 2011

Serialize an arbitary string to XML in .NET

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

From stackoverflow
  • 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);
    
  • 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 '\'
    

0 comments:

Post a Comment