# Replacing XML tag with a string based on parameters in tag?

**URL:** <https://www.ruby-forum.com/t/replacing-xml-tag-with-a-string-based-on-parameters-in-tag/171269>\
**Category:** Rails\
**Created:** [June 29, 2009, 8:33pm UTC](https://www.ruby-forum.com/t/replacing-xml-tag-with-a-string-based-on-parameters-in-tag/171269 "2009-06-29T20:33:43Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![yannimac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/7993a0/32.png) [@yannimac](https://www.ruby-forum.com/u/yannimac)\
**Post date:** [June 29, 2009, 8:33pm UTC](https://www.ruby-forum.com/t/replacing-xml-tag-with-a-string-based-on-parameters-in-tag/171269/1 "2009-06-29T20:33:43Z")

</div>

I am trying to figure out a (better) way to do the following:

some\_string = “Display a widget here - 1234”  
new\_string = replace\_widgets\_in\_string(some\_string)  
p new\_string =\> #Display a widget here - Widget 1234 is blue"

the method replace\_widgets\_in\_string will need to pick out the xml tag  
and value (which will be the model id) and from there I will find the  
model and return a string that replaces the widget tags.

Is there an existing library or easy way to do this that I might not be  
thinking of? I am assuming rexml wont work, since its not a well formed  
doc. I want to avoid coding a monolithic method using string splits.  
Any ideas?

---

<div class="post-metadata">

**Author:** ![yannimac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/y/7993a0/32.png) [@yannimac](https://www.ruby-forum.com/u/yannimac)\
**Post date:** [June 29, 2009, 9:20pm UTC](https://www.ruby-forum.com/t/replacing-xml-tag-with-a-string-based-on-parameters-in-tag/171269/2 "2009-06-29T21:20:54Z")

</div>

On Jun 29, 2009, at 11:33 AM, Yanni M. wrote:

> Is there an existing library or easy way to do this that I might not  
> be  
> thinking of? I am assuming rexml wont work, since its not a well  
> formed  
> doc. I want to avoid coding a monolithic method using string splits.  
> Any ideas?

Well, if you’re string will only ever contain one instance of the  
widget this would work…

> > some\_string =~ /\<(.\*?)\>(\d+)\</\1\>/  
> > =\> 24
> 
> > $1  
> > =\> “widget”
> 
> > $2  
> > =\> “1234”

Otherwise I’d look into hpricot/nokigirl and let it parse it.

-philip
