C# 如何创建并写入xml文件

来源:这里教程网 时间:2026-02-21 17:28:45 作者:

在C#中创建并写入XML文件,可以使用.NET提供的

System.Xml
命名空间中的类,比如
XmlDocument
XmlWriter
。下面介绍两种常用方法:使用
XmlDocument
和使用
XmlWriter

使用 XmlDocument 创建并写入 XML 文件

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 文件

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,选择取决于使用场景和个人偏好。

相关推荐