2014-11-08 65 views
0

使用下面的函數遞歸XML步行尋找空節點

var data = []; 
function recurseXML(node, path) { 
    var i, nodes; 
    if (node.hasChildNodes()) { 
     nodes = node.childNodes; 
     path += (path ? "." : "") + node.tagName 
     if (nodes.length < 2) { 
      recurseXML(nodes[0], path); 
     } else { 
      for (i = 0; i < nodes.length; i += 1) { 
       recurseXML(nodes[i], path + "[" + i + "]"); 
      } 
     } 
    } else { 
     data.push(path + " " + (node.nodeValue).trim()); 
    } 
} 

當我嘗試走XML in this fiddle它輸出好像還有空節點,但沒有

是什麼造成這一點,我該如何解決它?

+0

固定的小提琴鏈接 – SReject 2014-11-08 10:56:54

+1

不知道你的空節點是什麼意思? – 2014-11-08 11:10:41

回答

0

問題是我的節點之間的空格創建了一個空的文本節點。爲了解決這個問題我修剪多餘的空白節點之間的XML,前遞歸遍歷的XMLDOM:

document.body.innerHTML = (document.body.innerHTML).replace(/>\s+</g, '><');