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

C# 读写XML(代码分享)

程序员文章站 2023-11-22 14:08:40
读xml xmldocument xd = new xmldocument(); string filename = @"d:\test.xml"...

读xml

xmldocument xd = new xmldocument(); 
      string filename = @"d:\test.xml";
      xd.load(filename);
      xmlnodelist xmlnotelist = xd.getelementsbytagname("user");
      list<user> users = new list<user>();
     
      foreach (xmlelement item in xmlnotelist)
      {
        user user = new user();
        user.id = int.parse(item.getattribute("id"));
        xmlnodelist xnl = item.childnodes;
        user.name = xnl[0].innerxml;
        user.age =int.parse(xnl[1].innerxml);
        user.gender = xnl[2].innerxml;
        users.add(user);
      }
      foreach (var item in users)
      {
        console.writeline(item);
      }

read xml
<?xml version="1.0" encoding="gb2312"?>
<users>
  <user id='1'>
    <name >张三</name>
    <age>15</age>
    <gender>男</gender>
  </user>
  <user id='2'>
    <name>李四</name>
    <age>14</age>
    <gender>男</gender>
  </user>
</users>

test.xml

写xml

string filename =@"d:\test.xml";
      xmldocument xmldoc = new xmldocument();
      xmlnode header = xmldoc.createxmldeclaration("1.0","utf-8",null);
      xmldoc.appendchild(header);
      //创建一级节点
      xmlelement rootnode = xmldoc.createelement("users");
      list<user> list = getusers();
      foreach (var item in list)
      {
        xmlelement xn = inseruser(item,xmldoc);
        rootnode.appendchild(xn);
      }  
      xmldoc.appendchild(rootnode);
      xmldoc.save(filename);
    }
    /// <summary>
    /// 创建整个user的元素
    /// </summary>
    /// <param name="user"></param>
    /// <param name="xmldoc"></param>
    /// <returns></returns>
    private static xmlelement inseruser(user user, xmldocument xmldoc)
    {
      xmlelement xn = xmldoc.createelement("user");
      xn.setattribute("id", user.id + "");
      xn.appendchild(getxmlnode(xmldoc,"name",user.name));
      xn.appendchild(getxmlnode(xmldoc, "age", user.age + ""));
      xn.appendchild(getxmlnode(xmldoc, "gender", user.gender));
      return xn;
    }
    private static xmlelement getxmlnode(xmldocument xmldoc,string name,string value)
    {
      xmlelement xn = xmldoc.createelement(name);
      xn.innertext = value;
      return xn;
    }
    private static list<user> getusers()
    {
      list<user> list = new list<user>();
      for (int i = 0; i < 10; i++)
      {
        user user = new user();
        user.id = i;
        user.name = "name" + i;
        user.age = 15;
        user.gender = "男";
        list.add(user);
      }
      return list;
    }

write xml

实体类

class user
  {
    public int id { set; get; }
    public string name { get; set; }
    public int age { get; set; }
    public string gender { set; get; }
    public override string tostring()
    {
      return id +","+name + "," +age+"," + gender;
    }
  }

entity

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!