在.Net framework下遍历XML文挡树的两种算法
生活随笔
收集整理的這篇文章主要介紹了
在.Net framework下遍历XML文挡树的两种算法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在閱讀ASP.NET_XML深入編程技術?(PDF格式)一書的時候,發現遍歷樹的兩種算法:深度優先和廣度優先遍歷文擋樹,前一種需要使用遞歸,后者則不需要,本人大學時期數據結構學的不好,每每涉及到樹,總喜歡用遞歸,希望以后能根據需要選用一種,不過沒有時間再系統地學習數據結構了,那就平時多學多記吧!
另外這個例子不錯,還可以學到.net的XML DOM的一些操作方法.
?2??///?深度優先遍歷文擋樹(遞歸方法)
?3??///?</summary>
?4??///?<param?name="currentNode">當前節點</param>
?5??public?void?DOMDepthFirst(XmlNode?currentNode)
?6??{
?7???XmlNode?node?=?currentNode.FirstChild?;
?8???while?(?node?!=?null?)
?9???{
10????DOMDepthFirst(?node?)?;
11????node?=?node.NextSibling?;
12???}
13
14???//do?something?else?with?currentNode?herer
15??}
?1??/**////?<summary>
?2??///?廣度優先遍歷文擋樹(非遞歸)
?3??///?</summary>
?4??///?<param?name="root">遍歷的入口點,如果需要遍歷整個文擋則是XmlDocument對象</param>
?5??public?void?DOMBreadthFirst(XmlNode?root)
?6??{
?7???Queue?queue?=?new?Queue()?;
?8???queue.Enqueue(root)?;
?9???XmlNode?currentNode?=?null?;
10???try
11???{
12????while?(true)
13????{
14?????//如果queue為空,則拋錯,跳出try?section,這里是while循環的退出條件
15?????currentNode?=?(XmlNode)queue.Dequeue()?;
16
17?????if?(currentNode.HasChildNodes)
18?????{
19??????foreach?(XmlNode?child?in?currentNode.ChildNodes)
20??????{
21???????queue.Enqueue(child)?;
22??????}
23?????}
24????}
25???}
26???catch(System.InvalidOperationException?ex)
27???{
28????//throw?ex?;
29???}
30??}
31
32
使用方法:
???XmlDocument doc = new XmlDocument() ;
???doc.Load("test.xml") ;
???DOMDepthFirst(doc) ;
???DOMBreadthFirst(doc) ;
轉載于:https://www.cnblogs.com/kwklover/archive/2006/04/08/369888.html
總結
以上是生活随笔為你收集整理的在.Net framework下遍历XML文挡树的两种算法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 性能提高小技巧
- 下一篇: 更换桌面壁纸的小工具。