2012-03-29 8 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

うわー、私はこれに新しいですが、私は私を信じることができませんそれに気付かなかった。それは動作します。早速のご返事ありがとうございます。 –

+0

ありがとうたくさんの男.....トップラインは私の日を救った..... –

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/

関連する問題