日期:2014-05-17 浏览次数:20840 次
class XMLTester { #region 准备处理XML片段 /// <summary> /// /// </summary> /// <param name="fileFullPath"></param> public void processXML(string fileFullPath) { XmlDocument xmlDoc = new XmlDocument(); //给定了文件的全路径,载入文档 xmlDoc.Load(fileFullPath); //若给定的不是文件,而是XML字符串,可以如下得到Document //xmlDoc.LoadXml(xmlStr); // 此处是处理文档中的 //Resources//UIResource节点,这是一个XML片段 // XmlNode node = xmlDoc.DocumentElement.SelectSingleNode("//Resources//UIResource"); // 也可以处理整篇文档 XmlNode node = xmlDoc.DocumentElement; string rootString = node.Name; processNode(node, rootString); } public void processNode(XmlNode xmlNode,string rootStr) { if (xmlNode.HasChildNodes == true) { processBranchNode(xmlNode); processNode(xmlNode.FirstChild, rootStr); } else { processLeafNode(xmlNode); if (xmlNode.NextSibling != null) { processNode(xmlNode.NextSibling,rootStr); } else { int flag = 0; while (xmlNode.NextSibling == null) { if (xmlNode.Name == rootStr)//检查是否到了根节点,如果不检查会出现节点的引用错误 { flag = 1; break; } else { xmlNode = xmlNode.ParentNode; } } if (flag == 0) { if (xmlNode.Name != rootStr) processNode(xmlNode.NextSibling,rootStr); else Console.Write("process XML End=============================\r\n\r\n"); } else if (flag == 1) { Console.Write("process XML End=============================\r\n\r\n"); } } } } /// <summary> ///处理叶节点,可用 /// </summary> /// <param name="xmlNode"> 一个叶节点</param> private static void processLeafNode(XmlNode xmlNode) { Console.Write(" "+xmlNode.Name); Console.WriteLine(" is a leaf XML Node ,its first Attribute: key:"+xmlNode.Attributes[0].Name +"; Value:"+xmlNode.Attributes[0].Value); Console.Write(xmlNode.InnerText); Console.Write("\n"); } private static void processBranchNode(XmlNode xmlNode) { Console.Write(xmlNode.Name); Console.WriteLine(" has children; children count: " +xmlNode.ChildNodes.Count); Console.Write("\n"); } #endregion public static void Main() { XMLTester t = new XMLTester(); t.processXML(@"D:\test.xml"); Console.Read(); } }