簡體   English   中英

在.NET中將任意字符串字符串序列化為XML

[英]Serialize an arbitary string to XML in .NET

將序列化字符串(轉換為XML屬性或XML節點)到XML流的最佳方法是什么,以使XML保持有效(必須以某種方式對特殊字符,換行符等進行編碼)。

我將只使用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);

這不是CDATA在XML中要使用的確切含義嗎? 您需要注意的是您的數據不包含"]]>" ,或者您可以使用歷史悠久的C技術以某種方式對其進行轉義:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM