[英]How to replace text between two XML tags using jQuery or JavaScript?
I have a XML mark-up/code like the following. 我有一个XML标记/代码,如下所示。 I want to replace the text inside one of the tags (in this case <begin>...</begin>) using JavaScript or jQuery.
我想使用JavaScript或jQuery替换其中一个标签(在本例中为<begin> ... </ begin>)中的文本。
<part>
<begin>A new beginning</begin>
<framework>Stuff here...</framework>
</part>
The source is inside a textarea. 源在文本区域内。 I have the following code, but it is obviously not doing what I want.
我有以下代码,但是显然它没有按照我的要求做。
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
This is just appending to the existing text inside the begin tags. 这只是追加到begin标记内的现有文本。 I have a feeling this can be done only using Regex, but unfortunately I have no idea how to do it.
我觉得只能使用Regex才能做到这一点,但是不幸的是我不知道该怎么做。
You can use the parseXML() jQuery function, then just replace the appropriate node with .find()/.text() 您可以使用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());
Similar to the other answer, using the $.parseXML()
function, you could do this: 与其他答案类似,使用
$.parseXML()
函数,您可以这样做:
var xml = $.parseXML($("xml-code").val());
xml.find('begin').text('The same old beginning');
Note that there is no need to replace a whole node, just change it's text. 请注意,无需替换整个节点,只需更改其文本即可。 Also, this works if there are multiple
<begin>
nodes that need the text as well. 另外,如果有多个
<begin>
节点也需要文本,则此方法也有效。
You can user regular expression but better dont do it. 您可以使用正则表达式,但最好不要这样做。 Use DOM parsers.
使用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.