0
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?

4

1 回答 1

2

$(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)); 

​
于 2012-08-09T21:28:38.947 回答