2012-07-24 88 views
0

我有這樣一個XML字符串如下:?如何將XML節點轉換爲字符串?

str = "<myxml><Node id="1" attr1="a" attr2="b" /> 
<Node id="2" attr1="a" attr2="b" /><Node id="3" attr1="a" attr2="b" /> 
<Node id="4" attr1="a" attr2="b" /></myxml>" 

function returnNodeAsStr(str) { 
... 
... 
} 

if(returnNodeAsStr(str) == '<Node id="1" attr1="a" attr2="b" />') { 
    alert("ok"); 
} 

如何寫一個函數來獲取節點作爲字符串(使警報執行)

+0

如果你是真正的使用jquery,看看這個線程:http://stackoverflow.com/questions/510995/parse-xml-response-with-jquery – JMax 2012-07-24 08:48:29

回答

0

試試這個:

var str = '<myxml><Node id="1" attr1="a" attr2="b" /><Node id="2" attr1="a" attr2="b" /><Node id="3" attr1="a" attr2="b" /><Node id="4" attr1="a" attr2="b" /></myxml>'; 

function returnNodeAsStr(str) { 
    var xmlDoc = $.parseXML(str), 
     xml = $(xmlDoc), 
     item=[], 
     results=[]; 
    $(xml).find('Node').each(function() { 
     item.push("<Node"); 
     $.each(this.attributes, function(i, attrib){ 
      item.push(attrib.name+"=\""+attrib.value+"\""); 
     }); 
     item.push("/>"); 
     results.push(item.join(" ")); 
     item=[]; 
    }); 
    return results; 
} 

var result=returnNodeAsStr(str); 
console.log(result); 
/* 
["<Node id="1" attr1="a" attr2="b" />", 
"<Node id="2" attr1="a" attr2="b" />", 
"<Node id="3" attr1="a" attr2="b" />", 
"<Node id="4" attr1="a" attr2="b" />"] 
*/ 

if(result[0] == '<Node id="1" attr1="a" attr2="b" />') { 
    alert("ok"); 
} 
0

嘗試使用正則表達式這樣

var str='<myxml><Node id="1" attr1="a" attr2="b" /><Node id="2" attr1="a" attr2="b" /><Node id="3" attr1="a" attr2="b" /><Node id="4" attr1="a" attr2="b" /></myxml>'; 

var match = str.match(/<Node.*?\/>/g); 

if(match.length){ 
    for(var i=0; i< match.length; i++) 
     alert(match[i]);    
} 

不需要額外依賴關係

PS你甚至可以通過正則表達式得到個人ATTRS值,即使它會變得相當多毛

0

你可以試試這個:

var str = '<myxml><Node id="1" attr1="a" attr2="b" /><Node id="2" attr1="a" attr2="b" /><Node id="3" attr1="a" attr2="b" /><Node id="4" attr1="a" attr2="b" /></myxml>';​​​​​​​ 

var nodeArray = str.replace(/<\/?myxml>/g,'') //removing root-> '<myxml>' tag 
       .replace(/\/>\s*</g,'/>,<')  //replacing '/><' with '/>,<' 
       .split(',');      //spliting by comma -------^ 

在此之後,你將有Node字符串數組,你可以比較這些元素字符串,如:

if(nodeArray[0] == '<Node id="1" attr1="a" attr2="b" />'){ 
    //Do something 
}