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

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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 '\'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.