简体   繁体   中英

How to find and replace xml node value in JQuery

I need help in finding and replacing a value in xml node using JQuery, please suggest, below is my scenario,

var metaData ='<Control Type="Table" ID="4900a2a9-47d7-4d3b-9a35-fdd32b185730"></Control>
        <Control Type="TextBox"  ID="7a499af6-16c1-4fe8-9ea0-fe02e7eef886"></Control>';

in the above xml structure I want to search for ID="4900a2a9-47d7-4d3b-9a35-fdd32b185730" and replace it with ID="91e3cbe6-8168-40be-bf26-ccdd6acb1e17" in JQuery. Please suggest.

Below is what I tried,

var oldID = "4900a2a9-47d7-4d3b-9a35-fdd32b185730";
var newID = "91e3cbe6-8168-40be-bf26-ccdd6acb1e17";
metaData.replace(oldID, newID);

the above code was not successful.

Since you have just string in xml variable, use JS .replace()

xml.replace('4900a2a9-47d7-4d3b-9a35-fdd32b185730', '91e3cbe6-8168-40be-bf26-ccdd6acb1e17');

 var xml = '<Control Type="Table" ID="4900a2a9-47d7-4d3b-9a35-fdd32b185730"></Control><Control Type="TextBox" ID="7a499af6-16c1-4fe8-9ea0-fe02e7eef886"></Control>'; var result = xml.replace('4900a2a9-47d7-4d3b-9a35-fdd32b185730', '91e3cbe6-8168-40be-bf26-ccdd6acb1e17'); $("#from").text(xml); $("#result").text(result); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <b>Before:</b><br/> <div id='from'></div><br/> <b>After:</b><br/> <div id='result'></div> 

I wouldn't do a string replace.

 var xml = '<Control Type="Table" ID="4900a2a9-47d7-4d3b-9a35-fdd32b185730"></Control><Control Type="TextBox" ID="7a499af6-16c1-4fe8-9ea0-fe02e7eef886"></Control>'; var doc = $.parseXML('<root>' + xml + '</root>'); var $root = $(doc); $root.find('[ID="4900a2a9-47d7-4d3b-9a35-fdd32b185730"]').attr('ID', 'x'); var newxml = xmlToString(doc); $('#result').text(newxml.substring(6, newxml.length - 7)) //borrowed from http://stackoverflow.com/questions/6507293/convert-xml-to-string-with-jquery 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; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="result"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM