Looking for source code to XML-encode a string

D

Darryl R.

Everyone, I'm trying to create a JSP page that returns an XML string to the
caller (browser). Some of the elements will contain characters that should
be encoded before being added to the XML string (e.g. A&P should be changed
to A&P before it is added to the string). I'm looking for some code that
will do this, since the org.w3c.dom package doesn't seem to have any classes
with static methods that do this.

What I'm looking for is a the source code to create a method that accepts an
unencoded string and returns an encoded string. For example:

String s = "A&P";
String encodedS = encode(s);
//The method should return "A&P"

Any help would be greatly appreciated.

Thanks,
Darryl R.
 
L

La'ie Techie

What I'm looking for is a the source code to create a method that accepts
an unencoded string and returns an encoded string. For example:

String s = "A&P";
String encodedS = encode(s);
//The method should return "A&P"

public String encodeXML(String text)
{
int length = text.length;
StringBuffer work = new StringBuffer(length);
for ( int i=0; i < length; i++)
{
char c = text.charAt(i);
if ( c == '&')
work.append("&amp;");
else if ( c == '<' )
work.append("&lt;");
else if ( c == '>' )
work.append("&gt;");
else if ( c > 127 || Character.isISOControl(c) )
work.append("&#" + (int) c);
else
work.append(c);
}
return work.toString();
}

You could also use regular expressions, if you are using J2SE 1.4 . You
may want to encode the quotes.

Aloha,
La'ie Techie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top