使用C#对XML进行增删改查操作 收藏

时间:2022-10-20 23:33:33

xml文件格式

view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?> 
<messageList> 
  <message id="1"> 
    <Name>熊猫</Name> 
    <QQ>123456</QQ> 
    <Email>panda@qq.com</Email> 
    <Content>asfdsafasdfasdfsad我是内容</Content> 
    <Time>2009-10-1</Time> 
  </message> 
</messageList> 
<?xml version="1.0" encoding="utf-8"?>
<messageList>
  <message id="1">
    <Name>熊猫</Name>
    <QQ>123456</QQ>
    <Email>panda@qq.com</Email>
    <Content>asfdsafasdfasdfsad我是内容</Content>
    <Time>2009-10-1</Time>
  </message>
</messageList>

增加>>>>

view plaincopy to clipboardprint?
XmlDocument xmld = new XmlDocument();  
                xmld.Load(Server.MapPath("App_Code/Message.xml"));//加载xml文件   
                XmlNode root = xmld.SelectSingleNode("messageList");//查找messageList节点  
 
                int i = xmld.SelectSingleNode("messageList").ChildNodes.Count + 1;  
                XmlElement xml0 = xmld.createElement_x("message");  
                xml0.SetAttribute("id", i.ToString());  
 
                XmlElement xml1 = xmld.createElement_x("Name");//创建一个Name节点  
                xml1.InnerText = this.txtName.Value.Trim();  
                xml0.AppendChild(xml1);//添加  
 
                XmlElement xml2 = xmld.createElement_x("QQ");//创建QQ节点  
                xml2.InnerText = this.txtQQ.Value.Trim();  
                xml0.AppendChild(xml2);//添加  
 
                XmlElement xml3 = xmld.createElement_x("Email");//创建一个Email节点  
                xml3.InnerText = this.txtEmail.Value.Trim();  
                xml0.AppendChild(xml3);//添加