在.NET中构建XML文档的最佳方法是什么?

Ale*_*gas 3 .net xml

在.NET中创建XML文档似乎有很多选择.什么是最好的方法?

Dir*_*mar 5

如果你只需要生成XML(不需要解析或编辑),最快的方法就是使用XmlWriter(它比使用字符串的第二个例子更优雅,更快,更不容易出错,因为你不必担心保留你的文件格式良好):

// Create an XmlWriterSettings object with the correct options.
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = ("\t");
settings.OmitXmlDeclaration = true;

// Create the XmlWriter object and write some content.
using (var writer = XmlWriter.Create("data.xml", settings))
{
    writer.WriteStartElement("book");
    writer.WriteElementString("item", "tesing");
    writer.WriteEndElement();
    writer.Flush();
}
Run Code Online (Sandbox Code Playgroud)

如果你已经有一个要序列化的对象模型,你可以考虑使用XmlSerializer,但是 - 至少从我的经验来看 - 比XmlWriter慢得多,并且只能在简单的对象模型上使用.