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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Robert Dodier

    #1

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

    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

  • Joe Kesselman

    #2
    Re: need Java function to convert XML special chars &lt; &gt; to &amp;lt; &amp;gt;

    Robert Dodier wrote:[color=blue]
    > 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.[/color]

    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.

    --
    () ASCII Ribbon Campaign | Joe Kesselman
    /\ Stamp out HTML e-mail! | System architexture and kinetic poetry

    Comment

    Working...