C# 操作 XML 增 删 改 查 (转载)

C# 操作 XML 增 删 改 查

xml文件格式
<?xml version="1.0"?>
<dbGuest>
  
<User>
    
<Name uid="d">ew</Name>
    
<City>dsa</City>
    
<Email>eq</Email>
  
</User>
</dbGuest>
操作方式
//创建XML文件
        private void btnCreateXml_Click(object sender, System.EventArgs e)
        
{
            
//创建XML文档对象
            System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
            
//创建xml 声明节点
            System.Xml.XmlNode xmlnode = xmldoc.CreateNode(System.Xml.XmlNodeType.XmlDeclaration, """");
            
//添加上述创建和 xml声明节点
            xmldoc.AppendChild(xmlnode);
            
//创建xml dbGuest 元素(根节点)
            System.Xml.XmlElement xmlelem = xmldoc.CreateElement("""dbGuest""");


            xmldoc.AppendChild(xmlelem);
            
try
            
{
                xmldoc.Save(xmlFile);
            }

            
catch(Exception ex)
            
{
                
if(ex.Message.IndexOf("访问被拒绝"!= -1)
                
{
                    lblMsg.Text 
= "创建xml文档失败,没有写入权限,请检查xmldocs文件夹的写入权限!";
                    
return;
                }
                
            }

            lblMsg.Text 
= "xml文件创建成功";

            BindXMLFiles();
            GetXmlContent();
            BindUserNames();
            
        }

//添加用户
        private void btnAdd_Click(object sender, System.EventArgs e)
        
{
            
string uID = txtUID.Text;
            
string userName = txtUserName.Text;
            
string City = txtCity.Text;
            
string Email = txtEmail.Text;

            
if(!System.IO.File.Exists(xmlFile))
            
{
                lblMsg.Text 
= "xml文件"+xmlFile+"不存在,请先点击创建!";
                
return;
            }


            XmlDocument xmlDoc                
= new XmlDocument();
            xmlDoc.Load(xmlFile);    
//加载文件

            XmlNode root                    
= xmlDoc.SelectSingleNode("dbGuest");//查找<dbGuest>
            XmlElement xe_dbGuest_User        = xmlDoc.CreateElement("User");//创建一个<User>节点
            XmlElement xe_dbGuest_User_Name    = xmlDoc.CreateElement("Name");
            xe_dbGuest_User_Name.InnerText    
= userName;//设置文本节点
         
            XmlAttribute a                    
= xmlDoc.CreateAttribute("uid");//创建一个 属性
            a.Value                            = uID;
            xe_dbGuest_User_Name.Attributes.Append(a);
//增加一个属性
            xe_dbGuest_User.AppendChild(xe_dbGuest_User_Name);//添加到<User>节点中

            XmlElement xe_dbGuest_User_City    
= xmlDoc.CreateElement("City");//创建City节点
            xe_dbGuest_User_City.InnerText    = City;
            xe_dbGuest_User.AppendChild(xe_dbGuest_User_City);
//添加到<User>节点中

            XmlElement xe_dbGuest_User_Email    
= xmlDoc.CreateElement("Email");//创建Email节点
            xe_dbGuest_User_Email.InnerText    = Email;
            xe_dbGuest_User.AppendChild(xe_dbGuest_User_Email);
 
            root.AppendChild(xe_dbGuest_User);
//添加到<dbGuest>节点中
            xmlDoc.Save(xmlFile);//保存文件

            lblMsg.Text 
= "成功添加用户";

            GetXmlContent();

            BindXML();
            BindUserNames();

        }


//绑定xml数据
        private void BindXML()
        
{
            
if(!System.IO.File.Exists(xmlFile))
            
{
                lblMsg.Text 
= "xml文件"+xmlFile+"不存在,请先点击创建!";
                
return;
            }


//            方法一:通过ds 读取 xml
//            DataSet ds = new DataSet();
//            ds.ReadXml(xmlFile);
//            if(ds.Tables.Count > 0)
//            {
//                dgValue.DataSource = ds.Tables[0].DefaultView;
//                dgValue.DataBind();
//            }

            
//方法二
            DataTable dt = new DataTable();
            DataColumn dc 
= new DataColumn("uid");
            dt.Columns.Add(dc);            
            dc 
= new DataColumn("name");
            dt.Columns.Add(dc);
            dc 
= new DataColumn("city");
            dt.Columns.Add(dc);
            dc 
= new DataColumn("email");
            dt.Columns.Add(dc);

    
            
//将xml文件加载成xmlDoc
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(xmlFile);
            
//得到dbGust所有子节点
            XmlNodeList xnl=xmlDoc.SelectSingleNode("dbGuest").ChildNodes;
            
            
for(int i = 0 ; i < xnl.Count;i++)
            
{
                
//在每个子节点是遍历    xn 代表的是一个个User
                string uid = xnl.Item(i).ChildNodes[0].Attributes["uid"].Value;
                
string name = xnl.Item(i).ChildNodes[0].InnerText;
                
string city = xnl.Item(i).ChildNodes[1].InnerText;
                
string email = xnl.Item(i).ChildNodes[2].InnerText;

                DataRow dr 
= dt.NewRow();
                dr[
0= uid;
                dr[
1= name;
                dr[
2= city;
                dr[
3= email;
                dt.Rows.Add(dr);                
            }

            dgValue.DataSource 
= dt;
            dgValue.DataBind();


            
        }

//删除用户
        private void btnDelete_Click(object sender, System.EventArgs e)
        
{
            
string selectName = ddlNames.SelectedItem.Text;
            
string selectID = ddlNames.SelectedValue;

            XmlDocument xmlDoc 
= new XmlDocument();
            xmlDoc.Load(xmlFile);
            XmlNodeList xnl
=xmlDoc.SelectSingleNode("dbGuest").ChildNodes;
 
            
            
for(int i = 0 ; i < xnl.Count ; i++)
            
{
                XmlElement xe
=(XmlElement)xnl[i];//第i个dbGust子节点
                XmlNodeList node = xe.GetElementsByTagName("Name");
                
if(node.Count>0)
                
{
                    
//判断为用户选择的
                    if(node[0].InnerText==selectName && node[0].Attributes["uid"].Value == selectID)
                    
{
                        
string m = node[0].InnerText;
                        xmlDoc.SelectSingleNode(
"dbGuest").RemoveChild(node[0].ParentNode);//删除该User节点    
                        
//xe.RemoveAll();//删除该节点的全部内容 这二种有差别
                        
                        
break;
                        
                    }

                    
                }

            }

            
            
            xmlDoc.Save(xmlFile);
            BindXML();
            GetXmlContent();
            BindUserNames();

        }

//更新用户
        private void btnUpdate_Click(object sender, System.EventArgs e)
        
{
            
string selectName = ddlNames.SelectedItem.Text;
            
string selectID = ddlNames.SelectedValue;

            XmlDocument xmlDoc 
= new XmlDocument();
            xmlDoc.Load(xmlFile);
            XmlNodeList nodeList
=xmlDoc.SelectSingleNode("dbGuest").ChildNodes;//获取dbGuest节点的所有子节点
            foreach(XmlNode xn in nodeList)//遍历所有子节点
            {
                XmlElement xe
=(XmlElement)xn;//将子节点类型转换为XmlElement类型
            
                XmlNodeList node 
= xe.GetElementsByTagName("Name");
                
if(node.Count>0)
                
{

                    
//判断为用户选择的
                    if(node[0].InnerText==selectName && node[0].Attributes["uid"].Value == selectID)
                    
{
                        XmlNodeList nls
=xe.ChildNodes;//继续获取xe子节点的所有子节点
                        foreach(XmlNode xn1 in nls)//遍历
                        {
                            XmlElement xe2
=(XmlElement)xn1;//转换类型
                            if(xe2.Name=="Email")//如果找到Email属性
                            {
                                xe2.InnerText
="http://eflylab.cnblogs.com";//则修改
                                break;//找到退出来就可以了
                            }

                        }

                        
break;
                    }

                }

                
            }

            xmlDoc.Save(xmlFile);
            BindXML();
            GetXmlContent();
        }

//查询
        private void btnSelect_Click(object sender, System.EventArgs e)
        
{
            XmlDocument doc 
= new XmlDocument();
            doc.Load(xmlFile);

            
string selectName = ddlNames.SelectedItem.Text;

            
string email = doc.SelectSingleNode("//User[Name='"+selectName+"']").ChildNodes.Item(2).InnerText;
         
            
            lblMsg.Text 
= "查询"+selectName+"用户email为"+email;
        }

posted on 2008-08-27 09:13  Shuke  阅读(777)  评论(2编辑  收藏  举报

导航