欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

把list集合的内容写入到Xml中,通过XmlDocument方式写入Xml文件中

程序员文章站 2022-11-18 13:10:06
List list = new List { new Person{Name="张三",Age=20,Email="zs@zhansan.com"}, new Person{Name="李四",Age=30,Email="ls@lisi.com"}, new Pers ......

 

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);