我需要帮助才能使用JQuery查找和替换xml节点中的值,请在下面提供建议,
var metaData ='<Control Type="Table" ID="4900a2a9-47d7-4d3b-9a35-fdd32b185730"></Control>
<Control Type="TextBox" ID="7a499af6-16c1-4fe8-9ea0-fe02e7eef886"></Control>';
在上面的xml结构中我想搜索ID =&#34; 4900a2a9-47d7-4d3b-9a35-fdd32b185730&#34;并将其替换为ID =&#34; 91e3cbe6-8168-40be-bf26-ccdd6acb1e17&#34;在JQuery中。请建议。
以下是我的尝试,
var oldID = "4900a2a9-47d7-4d3b-9a35-fdd32b185730";
var newID = "91e3cbe6-8168-40be-bf26-ccdd6acb1e17";
metaData.replace(oldID, newID);
上述代码未成功。
答案 0 :(得分:1)
由于您只有xml
变量中的字符串,请使用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>
答案 1 :(得分:0)
我不会替换字符串。
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;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="result"></div>
&#13;