繁体   English   中英

如何使用jQuery或JavaScript在两个XML标签之间替换文本?

[英]How to replace text between two XML tags using jQuery or JavaScript?

我有一个XML标记/代码,如下所示。 我想使用JavaScript或jQuery替换其中一个标签(在本例中为<begin> ... </ begin>)中的文本。

<part>
 <begin>A new beginning</begin>
   <framework>Stuff here...</framework>
</part>  

源在文本区域内。 我有以下代码,但是显然它没有按照我的要求做。

code=$("xml-code").val();       // content of XML source
newBegin = "The same old beginning";    // new text inside <begin> tags
newBegin = "<begin>"+newBegin +"</begin>";   

code=code.replace("<begin>",newBegin);   // replace content

这只是追加到begin标记内的现有文本。 我觉得只能使用Regex才能做到这一点,但是不幸的是我不知道该怎么做。

您可以使用parseXML() jQuery函数,然后将相应的节点替换为.find()/。text()

var s = "<part><begin>A new beginning</begin><framework>Stuff here...</framework></part>";
var xmlDoc = $($.parseXML(s));
xmlDoc.find('begin').text('New beginning');
alert(xmlDoc.text());

http://jsfiddle.net/x3aJc/

与其他答案类似,使用$.parseXML()函数,您可以这样做:

var xml = $.parseXML($("xml-code").val());
xml.find('begin').text('The same old beginning');

请注意,无需替换整个节点,只需更改其文本即可。 另外,如果有多个<begin>节点也需要文本,则此方法也有效。

您可以使用正则表达式,但最好不要这样做。 使用DOM解析器。

var code = $('xml-code').html();            // content of XML source
var newBegin = "The same old beginning";    // new text inside <begin> tags

var regexp = new Regexp('(<part>)[^~]*(<\/part>)', i);
code = code.replace(regexp, '$1' + newBegin + '$2'); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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