答案:使用XmlDocument或XmlWriter可创建并写入XML文件。XmlDocument适合中小型数据,通过创建元素、属性并保存实现;XmlWriter适用于大型文件,以流式高效写入,需配置编码和缩进,二者均需注意编码与文件权限。

在C#中创建并写入XML文件,可以使用.NET提供的System.Xml命名空间中的类,比如XmlDocument或XmlWriter。下面介绍两种常用方法:使用XmlDocument和使用XmlWriter。
XmlDocument适合构建结构清晰的XML文档,操作直观,适合中小型XML数据。
XmlDocument对象示例代码:
using System;
using System.Xml;
<p>class Program
{
static void Main()
{
// 创建XML文档
XmlDocument doc = new XmlDocument();</p><pre class='brush:php;toolbar:false;'>    // 添加XML声明
    XmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "utf-8", null);
    doc.AppendChild(declaration);
    // 创建根元素
    XmlElement root = doc.CreateElement("Books");
    doc.AppendChild(root);
    // 创建子元素
    XmlElement book = doc.CreateElement("Book");
    book.SetAttribute("ID", "1");
    XmlElement title = doc.CreateElement("Title");
    title.InnerText = "C# 入门";
    book.AppendChild(title);
    XmlElement author = doc.CreateElement("Author");
    author.InnerText = "张三";
    book.AppendChild(author);
    // 添加到根节点
    root.AppendChild(book);
    // 保存到文件
    doc.Save("books.xml");
    Console.WriteLine("XML文件已创建并写入:books.xml");
}}
XmlWriter更高效,适合生成大型XML文件或需要流式写入的场景。
示例代码:
using System;
using System.Xml;
<p>class Program
{
static void Main()
{
// 设置写入参数(可选)
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.Encoding = System.Text.Encoding.UTF8;</p><pre class='brush:php;toolbar:false;'>    using (XmlWriter writer = XmlWriter.Create("books.xml", settings))
    {
        writer.WriteStartDocument(encoding: "utf-8");
        writer.WriteStartElement("Books");
        writer.WriteStartElement("Book");
        writer.WriteAttributeString("ID", "1");
        writer.WriteElementString("Title", "C# 入门");
        writer.WriteElementString("Author", "张三");
        writer.WriteEndElement(); // Book
        writer.WriteEndElement(); // Books
        writer.WriteEndDocument();
    }
    Console.WriteLine("XML文件已通过XmlWriter写入:books.xml");
}}
确保程序有写入目标目录的权限。若文件已存在,Save或Create会自动覆盖。
推荐使用using语句(如XmlWriter),确保资源正确释放。
若需中文不乱码,指定UTF-8编码。
基本上就这些,两种方式都能有效创建和写入XML,选择取决于使用场景和个人偏好。
以上就是C# 如何创建并写入xml文件的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号