Looking for source code to XML-encode a string

Discussion in 'Java' started by Darryl R., Aug 7, 2003.

  1. Darryl R.

    Darryl R. Guest

    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.
     
    Darryl R., Aug 7, 2003
    #1
    1. Advertising

  2. Darryl R.

    La'ie Techie Guest

    On Thu, 07 Aug 2003 17:50:20 +0000, Darryl R. wrote:

    > 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
     
    La'ie Techie, Oct 15, 2003
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. sincethe2004

    how to encode .aspx source code

    sincethe2004, Jun 13, 2004, in forum: ASP .Net
    Replies:
    1
    Views:
    394
  2. Soefara
    Replies:
    2
    Views:
    4,678
    Soefara
    Feb 11, 2004
  3. Warrick FitzGerald

    Encode XML

    Warrick FitzGerald, Aug 5, 2003, in forum: XML
    Replies:
    4
    Views:
    981
    Richard Tobin
    Aug 5, 2003
  4. Kee Nethery
    Replies:
    12
    Views:
    2,165
    Stefan Behnel
    Jun 27, 2009
  5. sumit
    Replies:
    0
    Views:
    392
    sumit
    Mar 10, 2012
Loading...

Share This Page