How Do I Convert Xml Nodes To String?
I've such a xml string as following: str = '
Solution 1:
try this:
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");
}
Solution 2:
Try using regexps like this
var str='<myxml><Nodeid="1"attr1="a"attr2="b" /><Nodeid="2"attr1="a"attr2="b" /><Nodeid="3"attr1="a"attr2="b" /><Nodeid="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]);
}
no additional dependencies required
P.S. you can even get individual attrs values via regexps, though it will become considerably hairier
Solution 3:
You may try this:
var str = '<myxml><Nodeid="1"attr1="a"attr2="b" /><Nodeid="2"attr1="a"attr2="b" /><Nodeid="3"attr1="a"attr2="b" /><Nodeid="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 -------^
After this you will have an array of Node
strings, and you can compare these elements with strings, e.g.:
if( nodeArray[0] == '<Nodeid="1"attr1="a"attr2="b" />'){
//Do something
}
Post a Comment for "How Do I Convert Xml Nodes To String?"