将任意字符串(到 XML 属性或 XML 节点)序列化为 XML 流以使 XML 保持有效(特殊字符、换行符等必须以某种方式编码)的最佳方法是什么。
最佳答案
我会简单地使用 DOM(例如 XmlDocument
或 XDocument
),或者对于大文件,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);
关于.net - 在 .NET 中将任意字符串序列化为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/771388/