在C#中创建简单的xml文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;


namespace CreateXml1107
{
        class Program
        {
      static void Main(string[] args)
      {
        Program app = new Program();
        app.CreateXmlFile();
      }
      public void CreateXmlFile()
      {
      XmlDocument xmlDoc = new XmlDocument();
      //创建类型声明节点
      XmlNode node=xmlDoc.CreateXmlDeclaration("1.0","utf-8","");
      xmlDoc.AppendChild(node);
      //创建根节点
      XmlNode root = xmlDoc.CreateElement("Users");
      xmlDoc.AppendChild(root);
      CreateNode(xmlDoc, root, "name", "heshaoqi");
      CreateNode(xmlDoc, root, "sex", "female");
      CreateNode(xmlDoc, root, "age", "23");
      try
      {
      xmlDoc.Save("c://users//98216//Desktop//data2.xml");
      }
      catch (Exception e)
      {
      //显示错误信息
      Console.WriteLine(e.Message);
      }
    }
    public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
    {
    XmlNode node=xmlDoc.CreateNode(XmlNodeType.Element,name,value);
    node.InnerText = value;
    parentNode.AppendChild(node);

    }
  }
}

【问题记录】

A1.不能写成 xmlDoc.Save("c:\users\98216\Desktop");(使用注释符号分开)

或者 xmlDoc.Save("c://users//98216//Desktop");除了存储位置还要写清文件名和格式

而要写成 xmlDoc.Save("c://users//98216//Desktop//data2.xml");;

A2. public void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)

        {

         XmlNode node=xmlDoc.CreateNode(XmlNodeType.Element,name,value);

         node.InnerText = value;

         parentNode.AppendChild(node);

          }

CreateNode内的参数要与上面定义的参数一一对应,原博客有遗漏

posted @ 2018-11-07 22:08  heshaoqi  阅读(3312)  评论(0编辑  收藏  举报