Gandalf
Gandalf

Reputation: 930

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

I have a XML mark-up/code like the following. I want to replace the text inside one of the tags (in this case <begin>...</begin>) using JavaScript or jQuery.

<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. I have a feeling this can be done only using Regex, but unfortunately I have no idea how to do it.

Upvotes: 1

Views: 1937

Answers (3)

arm.localhost
arm.localhost

Reputation: 479

You can user regular expression but better dont do it. Use DOM parsers.

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'); 

Upvotes: 0

Jerod Venema
Jerod Venema

Reputation: 44642

You can use the parseXML() jQuery function, then just replace the appropriate node with .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/

Upvotes: 2

loushou
loushou

Reputation: 1512

Similar to the other answer, using the $.parseXML() function, you could do this:

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.

Upvotes: 0

Related Questions