need Java function to convert XML special chars < > to &lt; &gt;

R

Robert Dodier

Hello,

Sorry for asking what must be a FAQ, but I wasn't able to find the
answer.

I have an XML document fragment which I want to store as a text string.
I want a function to convert any XML special characters such as < >
into
the corresponding character entities. I'm working with Java.

Thanks for any light you can shed on this problem.

Robert Dodier
 
J

Joe Kesselman

Robert said:
I have an XML document fragment which I want to store as a text string.
I want a function to convert any XML special characters such as < >
into
the corresponding character entities.

If you're using any of the standard XML tools (SAX, DOM, XSLT, ...) you
really shouldn't have to deal with any of that. They've already
implemented XML serializers which will do the right thing, and their
Java APIs let you just enter the text directly. In other words, if you
put a & character into a SAX characters() call, or into a DOM text node,
the XML serializer will automagically deal with converting it to &amp;
when you write that XML out.

If you really want a function... well, the easiest solution is to borrow
one from one of the open-source packages which already handles it, such
as the serializers in Xerces or Xalan. Note that it's a bit uglier than
it looks, since you may also have to deal with encoding issues unless
you're keeping everything in UTF-8 or UTF-16.
 

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,995
Messages
2,570,228
Members
46,816
Latest member
nipsseyhussle

Latest Threads

Top