XML遍历文档树(广度优先与递归)

/// <summary> /// 递归遍历文档树 /// </summary> /// <param name="currentNode"></param> public void DOMDepthFirst(XmlNode currentNode) { XmlNode node = currentNode.FirstChild; while (node != null) { DOMDepthFirst(node); node = node.NextSibling; } //do something else with currentNode herer } /// <summary>广度优先遍历文挡树(非递归)</summary> /// <param name="root">遍历的入口点,如果需要遍历整个文挡则是XmlDocument对象</param> public void DOMBreadthFirst(XmlNode root) { Queue queue = new Queue(); queue.Enqueue(root); XmlNode currentNode = null; try { while (true) { //如果queue为空,则抛错,跳出try section,这里是while循环的退出条件 currentNode = (XmlNode)queue.Dequeue(); if (currentNode.HasChildNodes) { foreach (XmlNode child in currentNode.ChildNodes) { queue.Enqueue(child); } } } } catch (System.InvalidOperationException ex) { //throw ex ; } } }

你可能感兴趣的:(xml,null,文档)