JQuery parseXML and Print


var usrconf = "<root><node>abc</node><node>efg</node></root>";
var xmlDoc = $.parseXML( usrconf );
$(xmlDoc).find('node').each(function(i) {
    // change node values here
});

现在如何打印更改的 XML?

$(this) 允许您访问在 each() 中选择的元素。 i是函数索引,如下所述:http://api.jquery.com/each/

.each( function(index, Element) )

所以正确的代码是:

var usrconf = "<root><node>abc</node><node>efg</node></root>";
var xmlDoc = $.parseXML( usrconf );
$(xmlDoc).find('node').each(function(i) {
 $(this).attr('changed', true);
});
console.log(xmlDoc);

或者,如果您想将其序列化回去

var usrconf = "<root><node>abc</node><node>efg</node></root>";
var xmlDoc = $.parseXML( usrconf );
$(xmlDoc).find('node').each(function(i) {
 $(this).attr('changed', true);
});
console.log(xmlDoc);
// from http://stackoverflow.com/a/6507766/141200
function xmlToString(xmlData) { 
    var xmlString;
    //IE
    if (window.ActiveXObject){
        xmlString = xmlData.xml;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else{
        xmlString = (new XMLSerializer()).serializeToString(xmlData);
    }
    return xmlString;
}   
console.log(xmlToString(xmlDoc)); 
​

最新更新