Skip to main content
Known Participant
May 17, 2009
Question

replace text in XML object using a sequence of tags as input

  • May 17, 2009
  • 1 reply
  • 1034 views

Hi, I need to write an apparently very simple function that replaces a text between tags in an XML object receving as input the sequence of tags to identify the element, but I miss one point.
I travel through the XML tree using a element variable like

Code:
element = element.child(n)

using at each step the tags provided as input to decide the value of "n". Now, when I reach the tags that contain the text to be replaced, what to do? If I use

Code:
element.replace(0, newValue)


I replace the text just in element  not in the original object...

For example having

<publishing_date>

       <year>2002</year>

       <month>Jan</month>

<success_date>

       <year>2004</year>

       <month>Feb</month>
</success_date>

I want to call a function like

replace(["success_date", "month"], "Mar")

and have an XML object where the second occurence of Feb is replaced with "Mar"

Any suggestion on this easy task?

Thanks a lot

Giuse

This topic has been closed for replies.

1 reply

Inspiring
May 19, 2009

From looking at the scripting guide you just need to assign the element a new value; Note I had add a root level as you didn't post the full xml tree

var newXml = new XML ( '<book><publishing_date><year>2002</year><month>Jan</month></publishing_date><success_date><year>2004</year><month>Feb</month></success_date></book>');
newXml..month[1] = 'mar';

or

newXml.success_date.month = 'mar';

Or did I misunderstand your question?

Known Participant
May 19, 2009

Hi Michael, thanks but my question was difference.

I need to make a function to operate with input tags, not with known tags. So I am writing a loop that scans the XML object using the tags provided in input until it reaches the desired tag with the text to be replaced.

That's why I wrote

element = element.child(n)

that I was thinking to use at each step of the loop looking for desired tag.

There I have the problem: if I use

element.replace.... I am changing the text between the tags in the element variable, not in the original XMLObject, and since there are no pointers in JavaScript, how to do that?

I hope to have been more clear now..... did I ?

Thanks and best reagrds

Giuseppe