如何将XML节点转换为字符串? [英] How do I convert XML nodes to string?
本文介绍了如何将XML节点转换为字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的XML字符串如下:
I've such a xml string as following:
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");
}
如何编写函数以将节点获取为字符串?(使警报执行)
How to write a function to get the node as string?(make the alert execute)
推荐答案
尝试一下:
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");
}
这篇关于如何将XML节点转换为字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文