Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

xml replace function

 
Devya Narayan
Greenhorn
Posts: 10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
We need to generate a xml file with data like this,
<person description="&lt;B&gt;Preethi&lt;/B&gt;" age="6"/>
<person description="&lt;B&gt;Devya&lt;/B&gt;" age="6"/&gt;

<B>Preethi</B> and <B>Devya</B> comes from DB.
So we wrote a replace function which replaces "<" tag with "&lt;",but this goes to infinite loop because we have one more replace function which replaces "&" with "&nbsp;".
How can i replace "<" with "&lt;"
">" with "&gt;"
"&" with "&nbsp;"
"'" with "&apos;" without any clash?

Thanks,
Devya
[ June 28, 2006: Message edited by: Jim Yingst ]
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13048
6
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When I had to do this sort of conversion I created a set of intermediate "place holder" tokens to avoid the infinite loop. It means an extra cycle of replaces but you get there eventually.
Bill
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Devya Narayan]: So we wrote a replace function which replaces "<" tag with "<",but this goes to infinite loop because we have one more replace function which replaces "&" with " "

Couldn't you just replace "&" with "&amp;" first? Then on any subsequent replacements, any new "&" which turn up will not be replaced.

The other way to do this is to have a single pass handle all the replacements. Loop through each character in the input and look it up in a Map (or array or switch statement) to determine what, if anything, it needs to be replaced with. Then write either the replacement, or the original character if no replacement exists.
 
Sergio Costa
Greenhorn
Posts: 3
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you considered XMLSerializer?

I tend to avoid re-inventing the wheel when at all possible.
 
Paul Clapham
Sheriff
Pie
Posts: 20196
26
MySQL Database
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Devya Narayan:
So we wrote a replace function which replaces "<" tag with "&lt;",but this goes to infinite loop because we have one more replace function which replaces "&" with "&nbsp;".
So do them in the opposite order. Replace "&" by "&amp;" first, then replace "<" by "&lt;".
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic