XML 生成一个XML文件

时间:2022-08-05 11:54:23
 public static void CreateXml(string path)
        {
            XmlDocument xmldoc = new XmlDocument();
            XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8);

            writer.WriteStartDocument();
            /*根节点*/
            writer.WriteStartElement("User");//根节点
            /*name*/
            writer.WriteStartElement("name");
            writer.WriteEndElement();
            /*password*/
            writer.WriteStartElement("password");
            writer.WriteEndElement();
            /*RememberPwd*/
            writer.WriteStartElement("RememberPwd");
            writer.WriteEndElement();
            /*Automatic_logon*/
            writer.WriteStartElement("Automatic_logon");
            writer.WriteEndElement();
            /*根节点*/
            writer.WriteEndElement();

            writer.WriteEndDocument();
            writer.Close();
            xmldoc.Load(path);

        }

方法二:

  public static void CreateXml2(string paths)
        {
            XmlDocument xmldoc = new XmlDocument();                     //首先创建 XmlDocument xml文档 
            XmlElement Config = xmldoc.CreateElement("Config");         //创建根节点 config   
            xmldoc.AppendChild(Config);                                 //把根节点加到xml文档中 

            XmlElement path = xmldoc.CreateElement("path");             //创建一个节点 path(用于做子节点) 
            path.InnerText = "这是path节点的文本内容";
            Config.AppendChild(path);                                   //将path添加为config的子节点  

            XmlElement ini = xmldoc.CreateElement("Ini");
            ini.InnerText = "1111";

            XmlAttribute timeout = xmldoc.CreateAttribute("timeout");   //创建一个属性timeout
            timeout.InnerText = "200";                                  //为属性timeout赋值为 200
            ini.Attributes.Append(timeout);                             //将属性timeout添加至Ini节点

            Config.AppendChild(ini);                                    //将Ini节点添加为Config的子节点

            xmldoc.Save(paths);

        }