using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Data; namespace Mtxfw.Utility { public class XmlClass { //构造函数 public XmlClass() { } public XmlDataDocument Create_doc(string xml_path) { //实例化XML操作类 XmlDataDocument doc = new XmlDataDocument(); try { //加载XML 文件 doc.Load(xml_path); } catch (Exception) { throw; } return doc; } /// /// 根据XML文件创建DataTable列的方法 /// /// /// /// public DataTable Table_Create(string xml_path, string rootNode) { //实例化XML操作对象类 XmlDataDocument doc = Create_doc(xml_path); //创建DataTable 类型的变量DT 用来存储读取的XML数据 DataTable dt = new DataTable(); //获取根节点 XmlNode root = doc.SelectSingleNode(rootNode); //循环创建DT列 foreach (XmlNode node in root.ChildNodes) { if (node.Name != "#comment") { dt.Columns.Add(node.Attributes["name"].Value, typeof(string)); } } return dt; } /// /// XML读取类 /// /// XML文件地址 /// 根节点名称 /// public DataTable Xml_Reader(string xml_path, string rootNode) { //实例化XML操作对象类 XmlDataDocument doc = Create_doc(xml_path); //创建DataTable 类型的变量DT 用来存储读取的XML数据 DataTable dt = new DataTable(); //获取根节点 XmlNode root = doc.SelectSingleNode(rootNode); //创建行 DataRow row = dt.NewRow(); //循环添加DT列 foreach (XmlNode node in root.ChildNodes) { if (node.Name != "#comment") { dt.Columns.Add(node.Attributes["name"].Value, typeof(string)); row[node.Attributes["name"].Value] = node.Attributes["value"].Value; } } dt.Rows.Add(row); return dt; } /// /// XML数据更新操作 /// /// XML路径 /// XML根节点 /// 数据更新Table public void Xml_Update(string xml_path, string rootNode, DataTable dt) { //实例化XML操作对象类 XmlDataDocument doc = Create_doc(xml_path); //获取根节点 XmlNode root = doc.SelectSingleNode(rootNode); //循环更新数据 foreach (XmlNode node in root.ChildNodes) { if (node.Name != "#comment") { node.Attributes["value"].Value = dt.Rows[0][node.Attributes["name"].Value].ToString(); } } //保存更讯 doc.Save(xml_path); } } }