c# xmlhelper 怎样创建XML文档

   2024-10-06 9730
核心提示:在C#中创建XML文档可以使用XmlDocument类或XDocument类。以下是使用XmlDocument类创建XML文档的示例:using System;using System

在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文档的结构和内容。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号