温馨提示×

如何使用c# xml生成文件

c#
小樊
82
2024-06-28 14:39:30
栏目: 编程语言

在C#中生成XML文件需要使用XmlDocument类。以下是一个简单的示例代码,演示如何使用C#创建一个名为"example.xml"的XML文件并添加节点和属性:

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        // 创建一个新的XML文档
        XmlDocument doc = new XmlDocument();

        // 创建XML声明
        XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(xmlDeclaration);

        // 创建根节点
        XmlElement root = doc.CreateElement("Root");
        doc.AppendChild(root);

        // 创建子节点
        XmlElement child = doc.CreateElement("Child");
        child.InnerText = "Hello World!";
        root.AppendChild(child);

        // 添加属性
        XmlAttribute attribute = doc.CreateAttribute("Attribute");
        attribute.Value = "Value";
        child.Attributes.Append(attribute);

        // 保存XML文件
        doc.Save("example.xml");

        Console.WriteLine("XML文件已生成!");
    }
}

运行以上代码后,会生成一个名为"example.xml"的XML文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
  <Child Attribute="Value">Hello World!</Child>
</Root>

通过这种方式,您可以使用C#创建并编辑XML文件。

0