一个用于读写XML文档的类

//writer:furenjun 2006.05.05
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

using System.Xml;
using System.Xml.Xsl;
using System.Xml.XPath;
using System.Text;
namespace MrfuReadAndWriteXmlFile
{
    
/// <summary>
    
/// C_MrFuXmlManager 的摘要说明。
    
/// </summary>

    public class C_MrFuXmlManager
    
{
        
public C_MrFuXmlManager()
        
{
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
        }


        
string myXmlFilePath=Application.StartupPath +@"\Users.xml";
        
string tempFilePath=Application.StartupPath +@"\Temp.xml";
        
public string GsXmlFilePath
        
{
            
get{return myXmlFilePath;}
            
set{myXmlFilePath=value;}
        }


        
XmlDocument Operation

        
/// <summary>
        
/// 按用户名查找用户的相关信息
        
/// </summary>
        
/// <param name="UserName"></param>
        
/// <returns></returns>

        public UserInfo GetUserInfo(string UserName)
        
{

            UserInfo usInfo
=new UserInfo();
            
            
if(this.GetNumOfChild(UserName)<0 )
                
return usInfo;

            XmlDocument xdoc
=new XmlDocument();
            xdoc.Load(
this.GsXmlFilePath );
            XmlNodeList xList
=xdoc.SelectNodes("//User[Name='"+UserName+"']");
            
foreach(XmlNode node in xList)
            
{
                XmlNodeReader NReader
=new XmlNodeReader(node);
                
try
                
{
                    
while(NReader.Read())
                    
{
                        
if(NReader.NodeType==XmlNodeType.Element)
                        
{
                            
if(NReader.HasAttributes)
                            
{
                                
while(NReader.MoveToNextAttribute())
                                
{
                                    
if(NReader.Value!="urn:UsersInfo")
                                    
{
                                        usInfo.Id
=NReader.Value;
                                    }

                                }

                            }

                        }

                        
if(NReader.Name=="Name")
                        
{
                            usInfo.Name 
=NReader.ReadString();
                        }

                        
else if(NReader.Name=="Pwd")
                        
{
                            usInfo.Pwd 
=NReader.ReadString();
                        }

                        
else if(NReader.Name=="AreaFlag")
                        
{
                            usInfo.AreaFlag 
=NReader.ReadString();
                        }

                        
else if(NReader.Name=="DateOfLastlogin")
                        
{
                            usInfo.DateOfLastlogin 
=NReader.ReadString();
                        }


                    }

                }

                
catch(Exception err)
                
{
                    
string errmsg="read xml file error \n"+err.ToString();
                    MessageBox.Show(errmsg);
                }

                
finally
                
{
                    
if(NReader!=null)
                    
{

                        NReader.Close();
                    }


                    
                }

                
            }

        
            
return usInfo;
        }


        
/// <summary>
        
/// 查找用户信息返回用户id的数据表
        
/// </summary>
        
/// <param name="UserName"></param>
        
/// <returns></returns>

        public  DataTable GetUserID(string UserName)
        
{
            
            DataTable dt
=new DataTable();
            
            
if(this.GetNumOfChild(UserName)<0 )
                
return dt;
            XmlDocument xdoc
=new XmlDocument();
            xdoc.Load(
this.GsXmlFilePath );
            
            XmlNodeList xList
=xdoc.SelectNodes("//User[Name='"+UserName+"']");//可以根据实际需要更改它的查找范围.如SelectNodes("//User")
        

            
if (xList.Count> 0)
            
{
                CreateColumns(dt, xList[
0]);
            }

            
foreach(XmlNode node in xList)
            
{
                DataRow dr
=dt.NewRow();
                
foreach(XmlAttribute attr in node.Attributes)
                
{
                    dr[attr.Name]
=attr.Value;
                }

                dt.Rows.Add(dr);
            }

            
return dt;
        }


        
/// <summary>
        
/// 创建列
        
/// </summary>
        
/// <param name="dt"></param>
        
/// <param name="node"></param>

        protected static void CreateColumns(DataTable dt, XmlNode node)
        
{
            
foreach(XmlAttribute attr in node.Attributes)
            
{
                dt.Columns.Add(
new DataColumn(attr.Name));
            }

        }

        


        
/// <summary>
        
/// 查找当前用户结点的位置
        
/// </summary>
        
/// <param name="UserName"></param>
        
/// <returns></returns>

        public int GetNumOfChild(string UserName)
        
{
            
if(!VerifyParameters())
                
return -1;
            
int i=-1;
            ArrayList myArylist
=new ArrayList(); 
            XmlDocument xdoc
=new XmlDocument();
            xdoc.Load(
this.GsXmlFilePath  );
            XmlNodeList xList
=xdoc.SelectNodes("//User");

            
int j=0;
            
int totalNum=xList.Count ;
            
bool find=false;
            
while((j<totalNum)&&(!find))
            
{
                
if(xList[j].ChildNodes.Item(0).InnerText.Trim()==UserName.Trim() )
                
{
                    i
=j;
                    find
=true;
                }

                j
++;
                
            }

            
return i;
        }


        
/// <summary>
        
/// 获取所有的用户名称 
        
/// </summary>
        
/// <returns></returns>

        public ArrayList GetTheNameOfAllUser( )
        
{
            ArrayList myArylist
=new ArrayList(); 
            XmlDocument xdoc
=new XmlDocument();
            xdoc.Load(
this.GsXmlFilePath  );
            XmlNodeList xList
=xdoc.SelectNodes("//User");
            
foreach(XmlNode xNode in xList)
            
{
                myArylist.Add(xNode.ChildNodes.Item(
0).InnerText); //也可显示文档中的其它项,更改item(i)即可
            }

            
return myArylist;
        }


        
/// <summary>
        
/// 更新指定用户的信息
        
/// </summary>
        
/// <param name="UserName"></param>
        
/// <param name="usInfo"></param>
        
/// <returns></returns>

        public bool UpdateNotes(string UserName,UserInfo usInfo)
        
{
            
if(this.GetNumOfChild(UserName)<0 )
                
return false;
            
try
            
{
                XmlDocument xdoc
=new XmlDocument();
                xdoc.Load(
this.GsXmlFilePath  );
            
                
//创建一个文档片断来存储要替换的节点
                XmlDocumentFragment xdocFrag=xdoc.CreateDocumentFragment();
                
//新节点的根节点
                XmlElement newElement=xdoc.CreateElement("User");
                XmlAttribute newID
=xdoc.CreateAttribute("Id");

                newID.Value
=usInfo.Id ;
                newElement.Attributes.SetNamedItem(newID);

                XmlElement newName
=xdoc.CreateElement("Name");
                newName.InnerText
=UserName;
                newElement.AppendChild(newName);

                XmlElement newPwd
=xdoc.CreateElement("Pwd");

                newPwd.InnerText
=usInfo.Pwd ;
                newElement.AppendChild(newPwd);

                XmlElement newAreaFlag
=xdoc.CreateElement("AreaFlag");
                newAreaFlag.InnerText
=usInfo.AreaFlag ;
                newElement.AppendChild(newAreaFlag);

                XmlElement newDateOfLastlogin
=xdoc.CreateElement("DateOfLastlogin");
                newDateOfLastlogin.InnerText
=System.DateTime.Now.ToString()  ;
                newElement.AppendChild(newDateOfLastlogin);

            
            
                
//把新创建的节点加入文档片断
                xdocFrag.AppendChild(newElement);
            
                
//确定要替换的节点作替换
                NameTable nametable=new NameTable();
                XmlNamespaceManager nameMan
=new XmlNamespaceManager(nametable);
                nameMan.AddNamespace(
"mrfu","urn:UsersInfo");

                XmlElement xUsers
=(XmlElement)xdoc.SelectSingleNode("//mrfu:Users",nameMan);
                
//找到该用户在文档中的结点序号(第几个孩子)
                int i=GetNumOfChild(UserName);
                
if(i>=0)
                
{
                    XmlElement xChild
=(XmlElement)xUsers.ChildNodes[i];
                    xUsers.ReplaceChild(xdocFrag.FirstChild,xChild);

                    xdoc.Save(
this.GsXmlFilePath );
                    
                }

                
else
                    
return false;

            }

            
catch
            
{
                
return false;
            }

            
return true;
        
        
        }


        
/// <summary>
        
/// 删除指定用户的纪录
        
/// </summary>
        
/// <param name="UserName"></param>
        
/// <returns></returns>

        public bool DeleteNotes(string UserName)
        
{
            
try
            
{
                XmlDocument xdoc
=new XmlDocument();
                xdoc.Load(
this.GsXmlFilePath  );

                NameTable nametable
=new NameTable();
                XmlNamespaceManager nameMan
=new XmlNamespaceManager(nametable);
                nameMan.AddNamespace(
"mrfu","urn:UsersInfo");

                XmlNode rootnode
=xdoc.SelectSingleNode("//mrfu:Users",nameMan);
                XmlNode node
=xdoc.SelectSingleNode("//User[Name='"+UserName+"']");
                rootnode.RemoveChild(node);
                xdoc.Save(
this.GsXmlFilePath );
            }

            
catch
            
{
                
return false;

            }

            
return true;
            
        }






        
/// <summary>
        
/// 验证xml文档的有效性
        
/// </summary>
        
/// <returns></returns>

        protected  bool VerifyParameters()
        
{
            
bool bls=true;
            
if (!System.IO.File.Exists (this.GsXmlFilePath ))
            
{
            
                bls
=false;
                
throw(new Exception("xmlFile do not exists."));
                
            }

            
else
            
{
                XmlDocument doc
=new XmlDocument();
                doc.Load(
this.GsXmlFilePath  );

                
if (doc == null)
                
{
                    bls
=false;
                    
throw new Exception("doc cannot be null.");
                
                }

                
if (doc.LastChild.GetType() == typeof(System.Xml.XmlDeclaration))
                
{
                    bls
=false;
                    
throw new Exception("XmlDocument requires at least the a root node");
                
                }

            }

            
return bls;
        }




    

        
/// <summary>
        
/// 获取当前根结点下的所有纪录值
        
/// </summary>
        
/// <returns></returns>

        public  DataTable GetDataFromXmlFile( )
        
{
            
            VerifyParameters();

            XmlDocument doc
=new XmlDocument();
            doc.Load(
this.GsXmlFilePath  );

            DataTable myTable
=new DataTable();
            
            XmlNodeList xList
=doc.SelectNodes("//User");

            
            
// create data table
            DataTable dt = new DataTable(); 

            
//读取它的元素名称
            
            dt.Columns.Add(
new DataColumn("Id"));
            dt.Columns.Add(
new DataColumn("Pwd"));
            dt.Columns.Add(
new DataColumn("AreaFlag"));
            dt.Columns.Add(
new DataColumn("DateOfLastlogin"));

            
//将各个元素对应的值一行一行写入表中
            DataRow row = null
            
            
foreach(XmlNode xNode in xList)
            
{
                row 
= dt.NewRow(); 
                
for(int j=0;j<4;j++)
                
{
                    row[j]
=xNode.ChildNodes.Item(j).InnerText; 
                }

                dt.Rows.Add( row ); 
                
            }

        
            dt.AcceptChanges(); 
            
return dt; 
            
        }


        
        
        

    }




    
public class UserInfo
    
{
        
public string   Id="";
        
public String   Name="";
        
public string   Pwd="";
        
public string   AreaFlag="";
        
public string   DateOfLastlogin="";
//        public String   Symbol="";
//        public double   Last;
//        public DateTime Date;
//        public double   Change;
//        public double   Open;
//        public double   High;
//        public double   Low;
//        public long     Volume;
//        public long     MarketCap;
//        public double   PreviousClose;
//        public double   PreviousChange;
//        public double   Low52Week;
//        public double   High52Week;
        
    }


}

原文地址:https://www.cnblogs.com/furenjun/p/401567.html