Two Methods for Traversing xml

Source: Internet
Author: User
// Preface
Function parseSrc (dataSrc ){
Var childNodes: Array = dataSrc. childNodes;
Var result: Array = new Array ();
For (var I = 0; I <childNodes. length; I ++ ){
Var element: XML = childNodes;
If (element. nodeType = 1 & element. hasChildNodes ()){
ParseSrc (element );
}
If (element. nodeType = 1 ){
Result. push (element );
Trace (element. nodeName );
Element. removeNode ();
} Else {
Trace (element + ", value:" + element. nodeValue );
Element. removeNode ();
}
}
}
// Middle Order
Function parseSrc (dataSrc: XML ){
Var childNodes: Array = dataSrc. childNodes;
Var result: Array = new Array ();
For (var I = 0; I <childNodes. length; I ++ ){
Var element: XML = childNodes;
Result. push (element. cloneNode (false ));
Trace (element. cloneNode (false ));
If (element. hasChildNodes ()){
ParseSrc (element );
}
}
}
// Non-recursive traversal. Visit the leaf first. Refer to the data structure tutorial.
Function preParse (node ){
Var work: Array = new Array (); // work Stack
Var result: Array = new Array (); // result Stack
For (; node. hasChildNodes () | work. length> 0 ;){
For (; node. hasChildNodes () & node. childNodes [0]. nodeType = 1 ;){
Work. push (node );
Node = node. childNodes [0];
}
Trace (node. nodeName );
Result. push (node );
If (work. length> 0 ){
Node. removeNode ();
// If there are nodes in the work stack, continue traversal. The node is retrieved from the root.
Node = work. pop ();
}
}
}

In terms of efficiency, I think recursion is more efficient than iteration. Because the optimization of vm in the stack segment is higher than that of the stack written manually

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.