Tuesday, December 1, 2009

Re: [jQuery] How to update the content of an XML node with JQuery

Easy, you're not working on the original xml string, you're working on a dom object generated using the string as original. It's not attached to your theXml variable anymore.

Michel Belleville


2009/12/1 karthick <mskarthick@gmail.com>
Hi Guys,

I have an simple xml dom (which is parsed from a string) like this

<PersonList>
       <Person>
              <PersonId>1</PersonId>
              <LocationId>1</LocationId>
              <AnswerId>1</AnswerId>
       </Person>
</PersonList>

Now using the jquery find() method I am able to get the value of
PersonId. But what I really want is to modify its value to 30

ie after updating the xml it should look like this

<PersonList>
       <Person>
              <PersonId >30</PersonId>
              <LocationId>1</LocationId>
              <AnswerId>1</AnswerId>
       </Person>
</PersonList>

Here is the code I am trying with

<script type="text/javascript">
var theXml = "<PersonList><Person><PersonId>1</PersonId><LocationId>1</
LocationId><AnswerId>1</AnswerId></Person></PersonList>";

$(document).ready(function(){

     $("#butSub").click(function(event){
              theXml = parseXml(theXml);
            $(theXml).find('Person').each(function(){
                           $(this).find('PersonId').text("30");
                           alert($(this).find('PersonId').text()); //This
alert shows the updated value 30 for PersonId node
                            });
            alert(theXml);   //This alert shows old value 1 for PersonId
node.
    });
 });
function parseXml(xml)
       {
               if (jQuery.browser.msie)
               {
                       var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                       xmlDoc.loadXML(xml);
                       xml = xmlDoc;
               }
               return xml;
       }
</script>


Could you guys tell me where I am going wrong? or Is there any other
better way of doing this?

I really really appreciate your help on this

Thank you
Karthick



No comments: