简体   繁体   English

在.NET中将任意字符串字符串序列化为XML

[英]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 : 我将只使用DOM(例如XmlDocumentXDocument ),或者对于大型文件使用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? 这不是CDATA在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: 您需要注意的是您的数据不包含"]]>" ,或者您可以使用历史悠久的C技术以某种方式对其进行转义:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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