温馨提示×

c# xmlhelper 怎样创建XML文档

c#
小樊
84
2024-07-15 16:31:37
栏目: 编程语言

在C#中创建XML文档可以使用XmlDocument类或XDocument类。以下是使用XmlDocument类创建XML文档的示例:

using System;
using System.Xml;

class Program
{
    static void Main()
    {
        // 创建XmlDocument对象
        XmlDocument xmlDoc = new XmlDocument();

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

        // 创建根节点
        XmlNode rootNode = xmlDoc.CreateElement("RootNode");
        xmlDoc.AppendChild(rootNode);

        // 创建子节点
        XmlNode childNode1 = xmlDoc.CreateElement("ChildNode1");
        childNode1.InnerText = "Value1";
        rootNode.AppendChild(childNode1);

        // 保存XML文档
        xmlDoc.Save("example.xml");
    }
}

使用XDocument类创建XML文档的示例:

using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        // 创建XDocument对象
        XDocument xDoc = new XDocument(
            new XDeclaration("1.0", "UTF-8", null),
            new XElement("RootNode",
                new XElement("ChildNode1", "Value1")
            )
        );

        // 保存XML文档
        xDoc.Save("example.xml");
    }
}

以上示例分别使用XmlDocument类和XDocument类创建了一个简单的XML文档,并保存为名为"example.xml"的文件。您可以根据实际需求进一步扩展和修改XML文档的结构和内容。

0