C#自定义处理xml数据类实例
本文实例讲述了C#自定义处理xml数据类。分享给大家供大家参考。具体分析如下:
这个C#类专门用户处理xml数据,可以大大简化xml的操作,类中封装了常用的xml操作,包括打开、读取xml数据,读取、写入节点数据,通过xpath读取节点数据,导出节点数据等等,还可以根据需要自己扩充类的功能。
usingSystem; usingSystem.Data; usingSystem.IO; usingSystem.Xml; namespaceDotNet.Utilities { publicclassXMLProcess { #region构造函数 publicXMLProcess() {} publicXMLProcess(stringstrPath) { this._XMLPath=strPath; } #endregion #region公有属性 privatestring_XMLPath; publicstringXMLPath { get{returnthis._XMLPath;} } #endregion #region私有方法 ///<summary> ///导入XML文件 ///</summary> ///<paramname="XMLPath">XML文件路径</param> privateXmlDocumentXMLLoad() { stringXMLFile=XMLPath; XmlDocumentxmldoc=newXmlDocument(); try { stringfilename=AppDomain.CurrentDomain.BaseDirectory.ToString()+XMLFile; if(File.Exists(filename))xmldoc.Load(filename); } catch(Exceptione) {} returnxmldoc; } ///<summary> ///导入XML文件 ///</summary> ///<paramname="XMLPath">XML文件路径</param> privatestaticXmlDocumentXMLLoad(stringstrPath) { XmlDocumentxmldoc=newXmlDocument(); try { stringfilename=AppDomain.CurrentDomain.BaseDirectory.ToString()+strPath; if(File.Exists(filename))xmldoc.Load(filename); } catch(Exceptione) {} returnxmldoc; } ///<summary> ///返回完整路径 ///</summary> ///<paramname="strPath">Xml的路径</param> privatestaticstringGetXmlFullPath(stringstrPath) { if(strPath.IndexOf(":")>0) { returnstrPath; } else { returnSystem.Web.HttpContext.Current.Server.MapPath(strPath); } } #endregion #region读取数据 ///<summary> ///读取指定节点的数据 ///</summary> ///<paramname="node">节点</param> ///使用示列: ///XMLProsess.Read("/Node","") ///XMLProsess.Read("/Node/Element[@Attribute='Name']") publicstringRead(stringnode) { stringvalue=""; try { XmlDocumentdoc=XMLLoad(); XmlNodexn=doc.SelectSingleNode(node); value=xn.InnerText; } catch{} returnvalue; } ///<summary> ///读取指定路径和节点的串联值 ///</summary> ///<paramname="path">路径</param> ///<paramname="node">节点</param> ///<paramname="attribute">属性名,非空时返回该属性值,否则返回串联值</param> ///使用示列: ///XMLProsess.Read(path,"/Node","") ///XMLProsess.Read(path,"/Node/Element[@Attribute='Name']") publicstaticstringRead(stringpath,stringnode) { stringvalue=""; try { XmlDocumentdoc=XMLLoad(path); XmlNodexn=doc.SelectSingleNode(node); value=xn.InnerText; } catch{} returnvalue; } ///<summary> ///读取指定路径和节点的属性值 ///</summary> ///<paramname="path">路径</param> ///<paramname="node">节点</param> ///<paramname="attribute">属性名,非空时返回该属性值,否则返回串联值</param> ///使用示列: ///XMLProsess.Read(path,"/Node","") ///XMLProsess.Read(path,"/Node/Element[@Attribute='Name']","Attribute") publicstaticstringRead(stringpath,stringnode,stringattribute) { stringvalue=""; try { XmlDocumentdoc=XMLLoad(path); XmlNodexn=doc.SelectSingleNode(node); value=(attribute.Equals("")?xn.InnerText:xn.Attributes[attribute].Value); } catch{} returnvalue; } ///<summary> ///获取某一节点的所有孩子节点的值 ///</summary> ///<paramname="node">要查询的节点</param> publicstring[]ReadAllChildallValue(stringnode) { inti=0; string[]str={}; XmlDocumentdoc=XMLLoad(); XmlNodexn=doc.SelectSingleNode(node); XmlNodeListnodelist=xn.ChildNodes;//得到该节点的子节点 if(nodelist.Count>0) { str=newstring[nodelist.Count]; foreach(XmlElementelinnodelist)//读元素值 { str[i]=el.Value; i++; } } returnstr; } ///<summary> ///获取某一节点的所有孩子节点的值 ///</summary> ///<paramname="node">要查询的节点</param> publicXmlNodeListReadAllChild(stringnode) { XmlDocumentdoc=XMLLoad(); XmlNodexn=doc.SelectSingleNode(node); XmlNodeListnodelist=xn.ChildNodes;//得到该节点的子节点 returnnodelist; } ///<summary> ///读取XML返回经排序或筛选后的DataView ///</summary> ///<paramname="strWhere">筛选条件,如:"name='kgdiwss'"</param> ///<paramname="strSort">排序条件,如:"Iddesc"</param> publicDataViewGetDataViewByXml(stringstrWhere,stringstrSort) { try { stringXMLFile=this.XMLPath; stringfilename=AppDomain.CurrentDomain.BaseDirectory.ToString()+XMLFile; DataSetds=newDataSet(); ds.ReadXml(filename); DataViewdv=newDataView(ds.Tables[0]);//创建DataView来完成排序或筛选操作 if(strSort!=null) { dv.Sort=strSort;//对DataView中的记录进行排序 } if(strWhere!=null) { dv.RowFilter=strWhere;//对DataView中的记录进行筛选,找到我们想要的记录 } returndv; } catch(Exception) { returnnull; } } ///<summary> ///读取XML返回DataSet ///</summary> ///<paramname="strXmlPath">XML文件相对路径</param> publicDataSetGetDataSetByXml(stringstrXmlPath) { try { DataSetds=newDataSet(); ds.ReadXml(GetXmlFullPath(strXmlPath)); if(ds.Tables.Count>0) { returnds; } returnnull; } catch(Exception) { returnnull; } } #endregion #region插入数据 ///<summary> ///插入数据 ///</summary> ///<paramname="path">路径</param> ///<paramname="node">节点</param> ///<paramname="element">元素名,非空时插入新元素,否则在该元素中插入属性</param> ///<paramname="attribute">属性名,非空时插入该元素属性值,否则插入元素值</param> ///<paramname="value">值</param> ///使用示列: ///XMLProsess.Insert(path,"/Node","Element","","Value") ///XMLProsess.Insert(path,"/Node","Element","Attribute","Value") ///XMLProsess.Insert(path,"/Node","","Attribute","Value") publicstaticvoidInsert(stringpath,stringnode,stringelement,stringattribute,stringvalue) { try { XmlDocumentdoc=newXmlDocument(); doc.Load(AppDomain.CurrentDomain.BaseDirectory.ToString()+path); XmlNodexn=doc.SelectSingleNode(node); if(element.Equals("")) { if(!attribute.Equals("")) { XmlElementxe=(XmlElement)xn; xe.SetAttribute(attribute,value); } } else { XmlElementxe=doc.CreateElement(element); if(attribute.Equals("")) xe.InnerText=value; else xe.SetAttribute(attribute,value); xn.AppendChild(xe); } doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString()+path); } catch{} } ///<summary> ///插入数据 ///</summary> ///<paramname="path">路径</param> ///<paramname="node">节点</param> ///<paramname="element">元素名,非空时插入新元素,否则在该元素中插入属性</param> ///<paramname="strList">由XML属性名和值组成的二维数组</param> publicstaticvoidInsert(stringpath,stringnode,stringelement,string[][]strList) { try { XmlDocumentdoc=newXmlDocument(); doc.Load(AppDomain.CurrentDomain.BaseDirectory.ToString()+path); XmlNodexn=doc.SelectSingleNode(node); XmlElementxe=doc.CreateElement(element); stringstrAttribute=""; stringstrValue=""; for(inti=0;i<strList.Length;i++) { for(intj=0;j<strList[i].Length;j++) { if(j==0) strAttribute=strList[i][j]; else strValue=strList[i][j]; } if(strAttribute.Equals("")) xe.InnerText=strValue; else xe.SetAttribute(strAttribute,strValue); } xn.AppendChild(xe); doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString()+path); } catch{} } ///<summary> ///插入一行数据 ///</summary> ///<paramname="strXmlPath">XML文件相对路径</param> ///<paramname="Columns">要插入行的列名数组,如:string[]Columns={"name","IsMarried"};</param> ///<paramname="ColumnValue">要插入行每列的值数组,如:string[]ColumnValue={"XML大全","false"};</param> ///<returns>成功返回true,否则返回false</returns> publicstaticboolWriteXmlByDataSet(stringstrXmlPath,string[]Columns,string[]ColumnValue) { try { //根据传入的XML路径得到.XSD的路径,两个文件放在同一个目录下 stringstrXsdPath=strXmlPath.Substring(0,strXmlPath.IndexOf("."))+".xsd"; DataSetds=newDataSet(); ds.ReadXmlSchema(GetXmlFullPath(strXsdPath));//读XML架构,关系到列的数据类型 ds.ReadXml(GetXmlFullPath(strXmlPath)); DataTabledt=ds.Tables[0]; DataRownewRow=dt.NewRow();//在原来的表格基础上创建新行 for(inti=0;i<Columns.Length;i++)//循环给一行中的各个列赋值 { newRow[Columns[i]]=ColumnValue[i]; } dt.Rows.Add(newRow); dt.AcceptChanges(); ds.AcceptChanges(); ds.WriteXml(GetXmlFullPath(strXmlPath)); returntrue; } catch(Exception) { returnfalse; } } #endregion #region修改数据 ///<summary> ///修改指定节点的数据 ///</summary> ///<paramname="node">节点</param> ///<paramname="value">值</param> publicvoidUpdate(stringnode,stringvalue) { try { XmlDocumentdoc=XMLLoad(); XmlNodexn=doc.SelectSingleNode(node); xn.InnerText=value; doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString()+XMLPath); } catch{} } ///<summary> ///修改指定节点的数据 ///</summary> ///<paramname="path">路径</param> ///<paramname="node">节点</param> ///<paramname="value">值</param> ///使用示列: ///XMLProsess.Insert(path,"/Node","Value") ///XMLProsess.Insert(path,"/Node","Value") publicstaticvoidUpdate(stringpath,stringnode,stringvalue) { try { XmlDocumentdoc=XMLLoad(path); XmlNodexn=doc.SelectSingleNode(node); xn.InnerText=value; doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString()+path); } catch{} } ///<summary> ///修改指定节点的属性值(静态) ///</summary> ///<paramname="path">路径</param> ///<paramname="node">节点</param> ///<paramname="attribute">属性名,非空时修改该节点属性值,否则修改节点值</param> ///<paramname="value">值</param> ///使用示列: ///XMLProsess.Insert(path,"/Node","","Value") ///XMLProsess.Insert(path,"/Node","Attribute","Value") publicstaticvoidUpdate(stringpath,stringnode,stringattribute,stringvalue) { try { XmlDocumentdoc=XMLLoad(path); XmlNodexn=doc.SelectSingleNode(node); XmlElementxe=(XmlElement)xn; if(attribute.Equals("")) xe.InnerText=value; else xe.SetAttribute(attribute,value); doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString()+path); } catch{} } ///<summary> ///更改符合条件的一条记录 ///</summary> ///<paramname="strXmlPath">XML文件路径</param> ///<paramname="Columns">列名数组</param> ///<paramname="ColumnValue">列值数组</param> ///<paramname="strWhereColumnName">条件列名</param> ///<paramname="strWhereColumnValue">条件列值</param> publicstaticboolUpdateXmlRow(stringstrXmlPath,string[]Columns,string[]ColumnValue,stringstrWhereColumnName,stringstrWhereColumnValue) { try { stringstrXsdPath=strXmlPath.Substring(0,strXmlPath.IndexOf("."))+".xsd"; DataSetds=newDataSet(); ds.ReadXmlSchema(GetXmlFullPath(strXsdPath));//读XML架构,关系到列的数据类型 ds.ReadXml(GetXmlFullPath(strXmlPath)); //先判断行数 if(ds.Tables[0].Rows.Count>0) { for(inti=0;i<ds.Tables[0].Rows.Count;i++) { //如果当前记录为符合Where条件的记录 if(ds.Tables[0].Rows[i][strWhereColumnName].ToString().Trim().Equals(strWhereColumnValue)) { //循环给找到行的各列赋新值 for(intj=0;j<Columns.Length;j++) { ds.Tables[0].Rows[i][Columns[j]]=ColumnValue[j]; } ds.AcceptChanges();//更新DataSet ds.WriteXml(GetXmlFullPath(strXmlPath));//重新写入XML文件 returntrue; } } } returnfalse; } catch(Exception) { returnfalse; } } #endregion #region删除数据 ///<summary> ///删除节点值 ///</summary> ///<paramname="path">路径</param> ///<paramname="node">节点</param> ///<paramname="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param> ///<paramname="value">值</param> ///使用示列: ///XMLProsess.Delete(path,"/Node","") ///XMLProsess.Delete(path,"/Node","Attribute") publicstaticvoidDelete(stringpath,stringnode) { try { XmlDocumentdoc=XMLLoad(path); XmlNodexn=doc.SelectSingleNode(node); xn.ParentNode.RemoveChild(xn); doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString()+path); } catch{} } ///<summary> ///删除数据 ///</summary> ///<paramname="path">路径</param> ///<paramname="node">节点</param> ///<paramname="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param> ///<paramname="value">值</param> ///使用示列: ///XMLProsess.Delete(path,"/Node","") ///XMLProsess.Delete(path,"/Node","Attribute") publicstaticvoidDelete(stringpath,stringnode,stringattribute) { try { XmlDocumentdoc=XMLLoad(path); XmlNodexn=doc.SelectSingleNode(node); XmlElementxe=(XmlElement)xn; if(attribute.Equals("")) xn.ParentNode.RemoveChild(xn); else xe.RemoveAttribute(attribute); doc.Save(AppDomain.CurrentDomain.BaseDirectory.ToString()+path); } catch{} } ///<summary> ///删除所有行 ///</summary> ///<paramname="strXmlPath">XML路径</param> publicstaticboolDeleteXmlAllRows(stringstrXmlPath) { try { DataSetds=newDataSet(); ds.ReadXml(GetXmlFullPath(strXmlPath)); if(ds.Tables[0].Rows.Count>0) { ds.Tables[0].Rows.Clear(); } ds.WriteXml(GetXmlFullPath(strXmlPath)); returntrue; } catch(Exception) { returnfalse; } } ///<summary> ///通过删除DataSet中指定索引行,重写XML以实现删除指定行 ///</summary> ///<paramname="iDeleteRow">要删除的行在DataSet中的Index值</param> publicstaticboolDeleteXmlRowByIndex(stringstrXmlPath,intiDeleteRow) { try { DataSetds=newDataSet(); ds.ReadXml(GetXmlFullPath(strXmlPath)); if(ds.Tables[0].Rows.Count>0) { ds.Tables[0].Rows[iDeleteRow].Delete(); } ds.WriteXml(GetXmlFullPath(strXmlPath)); returntrue; } catch(Exception) { returnfalse; } } ///<summary> ///删除指定列中指定值的行 ///</summary> ///<paramname="strXmlPath">XML相对路径</param> ///<paramname="strColumn">列名</param> ///<paramname="ColumnValue">指定值</param> publicstaticboolDeleteXmlRows(stringstrXmlPath,stringstrColumn,string[]ColumnValue) { try { DataSetds=newDataSet(); ds.ReadXml(GetXmlFullPath(strXmlPath)); if(ds.Tables[0].Rows.Count>0) { //判断行多还是删除的值多,多的for循环放在里面 if(ColumnValue.Length>ds.Tables[0].Rows.Count) { for(inti=0;i<ds.Tables[0].Rows.Count;i++) { for(intj=0;j<ColumnValue.Length;j++) { if(ds.Tables[0].Rows[i][strColumn].ToString().Trim().Equals(ColumnValue[j])) { ds.Tables[0].Rows[i].Delete(); } } } } else { for(intj=0;j<ColumnValue.Length;j++) { for(inti=0;i<ds.Tables[0].Rows.Count;i++) { if(ds.Tables[0].Rows[i][strColumn].ToString().Trim().Equals(ColumnValue[j])) { ds.Tables[0].Rows[i].Delete(); } } } } ds.WriteXml(GetXmlFullPath(strXmlPath)); } returntrue; } catch(Exception) { returnfalse; } } #endregion } }
希望本文所述对大家的C#程序设计有所帮助。