.net3.5及以上框架增强了对xml的支持,操作xml非常方便,下面分别用.net2.0及.net3.5及以上版本操作xml。
.net2.0版本读xml的demo:特别适用于配置文件的读取,类似于下面的这种情况:
<?xml version="1.0" encoding="utf-8"?> <SAP> <aa>编码</aa> <bb>名称</bb> </SAP>
代码:
/// <summary> /// 读取xml返回字典 /// </summary> /// <param name="xmlPath">绝对路径</param> /// <param name="nodeName">节点名</param> /// <returns></returns> public static Dictionary<string, string> GetAllData(string xmlPath, string nodeName) { XmlDataDocument xmlDoc = new XmlDataDocument(); xmlDoc.Load(xmlPath); XmlNode xn = xmlDoc.SelectSingleNode(nodeName); Dictionary<string, string> dic = new Dictionary<string, string>(); try { foreach (XmlNode xnf in xn) { XmlElement xe = xnf as XmlElement; dic.Add(xe.Name, xe.InnerText); } } catch (Exception) { return null; } return dic.Count > 0 ? dic : null; }
用linq读xml:
public ObservableCollection<Tree> GetTreeList() { try { XmlReader xmlReader = XmlReader.Create(new StringReader(xml)); XDocument xDocument = XDocument.Load(xmlReader); var quota = from p in xDocument.Descendants("ID").Descendants("PID").Descendants("Pic").Descendants("Name") select new Tree { Name = p.Attribute("Name").Value, ID = p.Attribute("ID").Value, Pic = p.Attribute("Pic").Value, PID = p.Attribute("PID").Value }; if (quota != null) { foreach (var item in quota) { Tree tree = new Tree { ID = item.ID, Name = item.Name, PID = item.PID, Pic = item.Pic }; treeList.Add(tree); } } return treeList; } catch (Exception) { throw; } }
对应xml为:
<?xml version="1.0" encoding="utf-8" ?> <Tree> <TreeNode ID="01" Name="sddd" PID="0" Pic="" ></TreeNode> <TreeNode ID="02" Name="ddd" PID="0" Pic="" ></TreeNode> <TreeNode ID="03" Name="dddd" PID="0" Pic="" ></TreeNode> <TreeNode ID="0121" Name="qqq" PID="01" Pic="" FontSize="12"></TreeNode> <TreeNode ID="0122" Name="tttt" PID="01" Pic="" FontSize="12"></TreeNode> <TreeNode ID="0123" Name="ttss" PID="01" Pic="" FontSize="12"></TreeNode> </Tree>
通过对比,显然高版本的.net framework操作xml简单方便得多,而且可读性强。