Modify xml in jquery

You can manipulate XML data in jquery according to your requirement. In simple word, you can change the value of an xml node or delete the particular node or insert a new node in your pervious xml.

In below example, there is list of country with their id. I have updated the value of country 1, delete the country 2 and insert a new country 3.

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('.btnChangeXML').click(function () {
        var xmlData = $.parseXML('<root><list><country cid="1">Japan</country><country cid="2">Pakistan</country></list></root>');
        var tempXML=$(xmlData);
        tempXML.find('country[cid="1"]').text('India');
        tempXML.find('country[cid="2"]').remove();
        tempXML.find('list').append('<country cid="3">Rusia</country>');
        $('#txtDisplay').val((new XMLSerializer()).serializeToString(xmlData));
      });

    });
  </script>
</head>
<body>
  <textarea id="txtDisplay" rows="5" cols="35"></textarea>
  <br />
  <button class="btnChangeXML">Change XML</button>
</body>
</html>

DISPLAY

1 comment :

  1. Oh yes, this worked for me, spent about half hour trying to find a good example and hey presto your page popped up. Thanks.

    ReplyDelete