aspose file tools*
The moose likes Java in General and the fly likes xml replace function Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "xml replace function" Watch "xml replace function" New topic
Author

xml replace function

Devya Narayan
Greenhorn

Joined: Feb 14, 2006
Posts: 10
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

Joined: Mar 22, 2000
Posts: 12823
    
    5
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

Joined: Jan 30, 2000
Posts: 18671
[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.


"I'm not back." - Bill Harding, Twister
Sergio Costa
Greenhorn

Joined: Jun 28, 2006
Posts: 3
Have you considered XMLSerializer?

I tend to avoid re-inventing the wheel when at all possible.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18907
    
    8

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
 
subject: xml replace function