2012-03-29 62 views
2

我通过$ .ajax()get获得以下类似XML的字符串。因为它无效,所以我不能使用dataType:'xml'或用$ .parseXML()解析。尽管使用xml作为字符串,并使用jQuery来遍历它似乎工作正常。我可以使用find()方法读取属性,但我似乎无法设置值。 (我只能得到XML,它是由另一个部门提供的,我无法对其进行更改)。使用jQuery设置XML字符串中的值

TLDR:需要操纵xml字符串。添加用户,密码和类型值,以便将其发送回服务器。

var xml = '<attrs xmlns="http://www.blah.com/abc/wxyz"><attr name="user" type="string"/><attr name="password" type="string"/><attr name="type" type="string" possibilities="typeOne,typeTwo,typeThree,typeFour">typeOne</attr></attrs>'; 

/* 
<attrs xmlns="http://www.blah.com/abc/wxyz"> 
    <attr name="user" type="string"/> 
    <attr name="password" type="string"/> 
    <attr name="type" type="string" possibilities="typeOne,typeTwo,typeThree,typeFour">typeOne</attr> 
</attrs> 
*/ 

// The following works fine. I get the possibilites, split them, and add them to a form: 
$.each($(xml).find('attr[possibilities]').attr('possibilities').split(','), function(index,value){ 
    options += '<option value="'+value+'">'+value+'</option>'; 
}); 

// I have tried the text(), prop(), and attr() methods. From what I've read you are supposed to use prop() instead of attr for setting values, but I tried attr anyway. 
$(xml).find('attr[name=user]').attr('textContent', 'TEST'); 
$(xml).find('attr[name=user]').text('TEST'); 
$(xml).find('attr[name=user]').prop('textContent', 'TEST'); 

// After attempting attr, text, and prop, the textContent property shows nothing (not undefined): 
console.log('textContent ' + $(xml).find('attr[name=user]').prop('textContent')); 

我在这方面比较新,所以有可能我的选择器是错的。任何帮助表示赞赏。提前致谢。

回答

4

每次调用$(xml)时,都会根据原始字符串创建一个新的dom对象。

试试这个:

j = $(xml); 
j.find('attr').attr('foo', 'bar'); 
console.log(j.html()); 

现在你解析XML字符串只有一次,更新所产生的节点。

+0

哇,我是新来的,但我不能相信我没有注意到这一点。这样可行。感谢您及时的回复。 – 2012-03-29 20:46:27

+0

非常感谢.....最上线拯救了我的一天..... – 2014-12-03 06:38:59

0

使用$ .parseXML,让您可以使用jQuery处理XML

例子:

var $xml=$($.parseXML(xml)); 
/* create a new xml node*/ 
var testAttr=$('<attr name="test"></attr>'); 
    /* append node to xml*/ 
$xml.find('attrs').append(testAttr); 
/* change an attribute in xml*/ 
$xml.find('attr[name="user"]').attr('type', 'Dynamically changed'); 

演示:http://jsfiddle.net/Ut5Gg/