简体   繁体   中英

Serialize an arbitary string to XML in .NET

将序列化字符串(转换为XML属性或XML节点)到XML流的最佳方法是什么,以使XML保持有效(必须以某种方式对特殊字符,换行符等进行编码)。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM