zoukankan      html  css  js  c++  java
  • 把list集合的内容写入到Xml中,通过XmlDocument方式写入Xml文件中

    List<Person> list = new List<Person>
    {
    new Person{Name="张三",Age=20,Email="zs@zhansan.com"},
    new Person{Name="李四",Age=30,Email="ls@lisi.com"},
    new Person{Name="王五",Age=22,Email="ww@wangwu.com"},
    new Person{Name="赵柳",Age=20,Email="xl@zhaoliou.com"},
    new Person{Name="玄武",Age=20,Email="xw@xuanwu.com"},
    new Person{Name="白虎",Age=20,Email="bh@baihu.com"},
    };

    //实例化XMLDocument对象
    XmlDocument xmldoc = new XmlDocument();

    //增加一个Xml文档声明

    XmlDeclaration xmldeclaration = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);

    //创建Xml文档根节点

    XmlElement xmlelement = xmldoc.CreateElement("List");

    //添加到Xml文档中
    xmldoc.AppendChild(xmlelement);

    //循环添加

    for (int i = 0; i < list.Count; i++)
    {

    //创建根节点下的子节点
    XmlElement xmlperson = xmldoc.CreateElement("Person");

    //创建子节点的属性ID
    XmlAttribute xmlattribute = xmldoc.CreateAttribute("id");

    //给属性值赋值
    xmlattribute.Value = (i + 1).ToString();

    //添加到子节点中
    xmlperson.Attributes.Append(xmlattribute);

    //添加Name节点

    XmlElement xmlName = xmldoc.CreateElement("Name");

    //给Name文本赋值
    xmlName.InnerText = list[i].Name;

    //添加到Person节点下
    xmlperson.AppendChild(xmlName);

    //以下节点类似

    XmlElement xmlAge = xmldoc.CreateElement("Age");
    xmlAge.InnerText = list[i].Age.ToString();
    xmlperson.AppendChild(xmlAge);

    XmlElement xmlEmail = xmldoc.CreateElement("Email");
    xmlEmail.InnerText = list[i].Email;
    xmlperson.AppendChild(xmlEmail);

    xmlelement.AppendChild(xmlperson);

    }

    //创建文件保存在Xml文件夹中

    string fileName = Server.MapPath("/Xml/List.xml");

    xmldoc.Save(fileName);

  • 相关阅读:
    媒体查询
    H5 progress标记
    sqlite数据库常用语句
    C#导出Word文档开源组件DocX
    bat实现监控进程守护程序-保证平台服务的稳定执行
    windows开机自动执行bat脚本启动cmd命令窗口并执行命令,最后自动关闭cmd命令窗
    Python实现定时执行任务的三种方式简单示例
    bat实现守护程序保证平台正常运行
    Windows CMD命令大全
    Windows下使用批处理文件.bat删除旧文件
  • 原文地址:https://www.cnblogs.com/libo-2249/p/10061073.html
Copyright © 2011-2022 走看看