1

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.

3
  • Xml editting with Regex sounds logical, but isn't. Only xml structures that are not very complex can be eddited by regex. Can you give us the example text and the result you want? Commented Dec 24, 2013 at 20:04
  • You are creating a new problem, which doesn't have to be there. You should try to access the DOM in the node-tree. Therein you can access the node's text :) Commented Dec 24, 2013 at 20:04
  • DOM manipulation: api.jquery.com/category/manipulation Commented Dec 24, 2013 at 20:07

3 Answers 3

2

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/

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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

1 Comment

Thanks. I would like to explorer the idea of Regex, since the XML can change in format. Is it possible for you to create a fiddle. I tried your code, but it is not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.