Two Algorithms for traversing the XML text block tree under. Net

Source: Internet
Author: User
Traverse the text block tree in depth first (recursive method ):

1/** // <summary>
2 // traverse the text block tree in depth first (recursive method)
3 /// </summary>
4 /// <param name = "currentNode"> current node </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}

SPAN first traverses the text block tree (non-recursive)

1/** // <summary>
2 // The width first traverses the text block tree (non-recursive)
3 /// </summary>
4 // <param name = "root"> the traversal entry point. If you want to traverse the entire document block, it is an XmlDocument object. </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 // If the queue is empty, an error is thrown out of the try section. Here is the exit condition of the while loop.
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

Usage:

XmlDocument doc = new XmlDocument ();
Doc. Load ("test. xml ");
DOMDepthFirst (doc );
DOMBreadthFirst (doc );

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.