1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Xml; 6 7 namespace ZW.ClassLibrary 8 { 9 public class XmlHelpers 10 { 11 /// <summary> 12 /// XML文档 13 /// </summary> 14 XmlDocument xd = new XmlDocument(); 15 16 /// <summary> 17 /// 从文件中获取XmlDocument对象 18 /// </summary> 19 /// <param name="file">xml文档</param> 20 /// <param name="type">文档类型</param> 21 public XmlHelpers(string file, string type) 22 { 23 if (type == "path") 24 { 25 XmlTextReader xr = new XmlTextReader(file); 26 xd.Load(xr); 27 xr.Close(); 28 } 29 30 if (type == "text") 31 { 32 xd.LoadXml(file); 33 } 34 } 35 36 /// <summary> 37 /// 获取第一个匹配节点的属性值 38 /// </summary> 39 /// <param name="nodePath"></param> 40 /// <param name="attrName"></param> 41 /// <returns></returns> 42 public string GetAttribute(string nodePath, string attrName) 43 { 44 XmlNode xn = xd.SelectSingleNode(nodePath); 45 if (xn == null) //检测节点是否存在 46 { 47 return ""; 48 } 49 if (xn.Attributes[attrName] == null) //检测属性是否存在 50 { 51 return ""; 52 } 53 54 return xn.Attributes[attrName].Value; 55 } 56 57 /// <summary> 58 /// 获取某个节点 59 /// </summary> 60 /// <param name="nodePath"></param> 61 /// <returns></returns> 62 public XmlNode GetNode(string nodePath) 63 { 64 XmlNode xn = xd.SelectSingleNode(nodePath); 65 return xn; 66 } 67 68 /// <summary> 69 /// 获取某个节点子集合指定属性值的节点 70 /// </summary> 71 /// <param name="nodePath">父节点</param> 72 /// <returns></returns> 73 public XmlNode GetNode(string nodePath, string attrName, string attrValue) 74 { 75 XmlNodeList xl = GetChildNode(nodePath); 76 if (xl != null) 77 { 78 foreach (XmlNode node in xl) 79 { 80 if (node.Attributes[attrName] != null) //检测属性是否存在 81 { 82 if (node.Attributes[attrName].Value.Trim() == attrValue) 83 { 84 return node; 85 } 86 } 87 } 88 } 89 return null; 90 } 91 92 /// <summary> 93 /// 获取某个节点上的子节点 94 /// </summary> 95 /// <param name="nodePath"></param> 96 /// <returns></returns> 97 public XmlNodeList GetChildNode(string nodePath) 98 { 99 XmlNodeList xl = null; 100 XmlNode xn = xd.SelectSingleNode(nodePath); 101 if (xl != null) 102 { 103 xl = xd.ChildNodes; 104 } 105 return xl; 106 } 107 } 108 }