How to encode a string containing HTML

I have a string which contains HTML tags. This will be written to file so i need to encode it i guess to ISO-8859-1
Please note: i am using JDK1.2.2
My code is
bytes = new byte[(int)rs.getString(k).length()*4];
desc = new String(bytes, "ISO-8859-1");     
This does not work. The tags remain the same i.e. "<" and ">" are still there in the String. In what format should HTML be encoded and what am i doing wrong above?

or...
      * Encodes any special characters in the specified string with their
      * entity equivalents. 
      * @param  str  the original string
      * @return  the encoded string
     public static String encodeEntities(String str) {
          StringBuffer sb = new StringBuffer(str);
          // must replace '&' first
          char[] chars = {     // list of characters to replace
               '&',      '<',      '>',      '\'',      '\"'
          String[] ents = {     // list of entities to replace with
               "&",      "<",      ">",      "&apos;", """
          int len = Math.min(chars.length, ents.length);
          for(int i = 0; i < len; i++) {
               for(int j = 0; j < sb.length(); j++) {
                    if(sb.charAt(j) == chars) {
                         sb.replace(j, j+1, ents[i]);
          return sb.toString();
     * Decodes any entities in the specified string with their character
     * equivalents.
     * @param str the encoded string
     * @return the decoded string
     public static String decodeEntities(String str) {
          if(str == null) {
               return null;
          StringBuffer sb = new StringBuffer(str);
          String[] ents = {     // list of entities to replace
               "&",      "<",      ">",      "&apos;", """
          String[] chars = {     // list of characters to replace with
               "&",      "<",      ">",      "\'",      "\""
          int len = Math.min(chars.length, ents.length);
          int k = 0;
          for(int i = 0; i < len; i++) {
               for(int j = 0; j < sb.length(); j++) {
                    k = j + ents[i].length();
                    if(k >= sb.length()) {
                         break;
                    if(sb.substring(j, k).equals(ents[i])) {
                         sb.replace(j, k, chars[i]);
          return sb.toString();

Similar Messages

  • How to encode sql string for SQL Server when using JDBC?

    in code, dynamically generate sql stirng like:
    String sqlstring = "select column from table where column=' " + var + " ' ";
    Question is: if var include char ' , it will cause error becuase ' is reserved by SQL Server for string reference.
    So how to encode string for dynamic sql string? for example, following sql(when var =" I'm tester"):
    select column from table where column like ' I'm tester '
    Edited by: KentZhou on Jun 17, 2009 3:10 PM

    Use PreparedStatement. Use it all the way. It not only saves you from SQL injections, but also eases setting non-standard Java objects like Date and InputStream in a SQL statement.
    Prepare here: [http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html].

  • How to parse a string containing xml data

    Hi,
    Is it possible to parse a string containing xml data into a array list?
    my string contains xml data as <blood_group>
         <choice id ='1' value='A +ve'/>
         <choice id ='2' value='B +ve'/>
             <choice id ='3' value='O +ve'/>
    </blood_group>how can i get "value" into array list?

    There are lot of Java XML parsing API's available, e.g. JAXP, DOM4J, JXPath, etc.
    Of course you can also write it yourself. Look which methods the String API offers you, e.g. substring and *indexOf.                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to determine if string contains HashSet item using LINQ

    Hi,
    I know how to iterate through a HashSet to see if an item is contained in a string.  But, I can't quite figure out how to do it with LINQ.
    Something like if( string.Contains(???))
    I would appreciate any help!
    Thanks much!!

    Thanks everyone.  I like the examples posted above.
    Actually, what I want to know is if any HashSet values can be found in a string using LINQ
    HashSet<string> terminals = new HashSet<string>();
    terminals.Add("FD4A");
    terminals.Add("FD4B");
    terminals.Add("FD4C");
    //a collection of a bunch of transactions done at various terminals
    List<string> transactionList = new List<string>();
    foreach (string transaction in transactionList)
        foreach (string terminal in terminals)
           if (transaction.Contains(terminal) == true)
                //this is one of the transactions I want - do something
                break;
    Thanks much and have a great weekend!!

  • How to Identify whether string contains only numbers

    Hi Experts,
    How to identify whether a string contains only numbers...
    Thanks & Regards,
    Neeraj.

    Hi Neeraj,
    ISNUMERIC(String_Field)
    The above function returns '0' for non-numerics and
    '1' for numeric
    Hope this helps.
    Regards,
    Bala

  • How to insert a string containing a single quote to the msql database? help

    how can i insert a string which contains a single quote in to database... anyone help
    Message was edited by:
    sijo_james

    Absolutely, Positively use a PreparedStatement. Do not use sqlEscape() function unless you have some overriding need (and I don't know what that could possibly be).
    There are 1000's of posts on the positive aspects of using a PreparedStatement rather than using a Statement. The two primary positive attributes of using a PreparedStatement are automatic escaping of Strings and a stronger security model for your application.

  • How to encode a string to base64 in java ?

    Hi, I want to send my user name to my SMTP server encoded in base64 .
    How do I do this ??
    Ramesh

    Ok I wait for you.
    I guess the following covert a string to base 8
    String userName ="Ramesh"
    byte[] strBytes = userName.getBytes("UTF-8");
    I do not know about base64.
    I need this urgently because I am sending my user name and password to my SMTP server and they should be encoded in base64.
    Please help.
    Ramesh

  • How check if a string contains a generic character?

    I want know how i can check if this string
    String mio= new String("Error 101");contains this substring
    1xxwhere "xx" are two generic characters that follow "1".
    Thanks
    Message was edited by:
    PremierITA

    Use a regular expression.Pattern threeDigitNumberThatStartsWith1 = Pattern.compile(".*1\\d\\d.*");
    Matcher matcher = pattern.matcher(mio);
    if(matcher.matches()) {
      // found it!
    else {
      // didn't find it
    }More about pattern matching here: http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html

  • How to change inner content of HTML tag using HTMLDocument?

    I want to change the inner content of an HTML tag from a HTMLDocument. The tag is like
    <span id ="id1">Replace me</span>.
    So I want to change the text "Replace me" inside the span tag and replace it with an other text.
    I can get the span element using
    HTMLDocument.getElement("id1")
    I have tried many things with the Element instance i got from getElement. But I find no way to change the inner content of the HTML element. Any ideas?

    If I use JDK 1.5 the SPAN tag works, so I checked the core of the problem which is inserting HTML code in an HTML tag.
    setInnerHTML works fine for block tags like DIV but not if the tag is a leaf element like the SPAN tag. I have tried to use the following code for leaf elements:
    Element elem = m_htmlDocument.getElement(id);
    int nStartOffest = elem.getStartOffset();
    int nEndOffset = elem.getEndOffset();
    int nLength = nEndOffset - nStartOffest;
    m_htmlDocument.replace(nStartOffest, nLength, html, elem.getAttributes());
    This works, but only if the new HTML string does not contain HTML tags like a link <href..... >. If the string contains HTML tags the replace method masks all characters like < or >. So the link is not shown as link in the HTML page but as HTML text.
    The next thing I have tried is using
    m_htmlDocument.setOuterHTML(elem, html);
    This works too but it replaces the whole original HTML element like the SPAN tag.
    So there is still the question how to insert HTML text into a leaf Element in a HTMLDocument.

  • How to send query string to OSB Business Service?

    Hi
    I need to call a Servlet which is accepting http get request.
    My system design is
    I have a web service interface that I need to expose to Front end application. I am using Proxy service for this.
    Then I have a servlet at end system and using Business service to send request to servlet.
    I need to pass username, password, jndi context and payload using url encoding.
    What all steps do I need to follow for this? How to create query string , which variable I need to play with inbound or outbound?
    I have gone through all the answers on this forum but could not understand much.
    Thanks
    Vibhor

    Hii
    I am still unable to send http get request to end service.
    In flow I have setted $outbound/transport/request-http/query-string too.
    But I have to send request with url encoding.
    How to encode query string and how can I check whether my request is going correctly or not, is there any variable in which complete url would be stored.
    Thanks
    Vibhor
    Edited by: Vibhor Rastogi on Sep 15, 2010 9:49 AM

  • Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string co

    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs. at Error$/throwError() at flash.net::URLVariables/decode() at flash.net::URLVariables() at flash.net::URLLoader/onComplete() _________________________________________________________________________________________ _____________________ stop(); var DepartVars:URLVariables = new URLVariables(); var DepartURL:URLRequest = new URLRequest("scripts/www.mywebsite.com/depart.php"); DepartURL.method = URLRequestMethod.POST; DepartURL.data = DepartVars; var DepartLoader:URLLoader = new URLLoader; DepartLoader.dataFormat = URLLoaderDataFormat.VARIABLES; DepartLoader.addEventListener(Event.COMPLETE, completeDepart); depart_btn.addEventListener(MouseEvent.CLICK, DepartUser); // Function to run when the Depart button is pressed function DepartUser (event:MouseEvent):void{             // Ready the variables here for sending to PHP           DepartVars.post_code = "Depart";         // Send the data to the php file           DepartLoader.load(DepartURL);         welcome_txt.text = "Processing request...Bon Voyage"; } // Close DepartUser function /////////////////////////////////////// // Function for when the PHP file talks back to flash function completedepart(event:Event):void{     if (event.target.data.replyMsg == "success") {             var refreshPage:URLRequest = new URLRequest("javascript:NewWindow=window.location.reload(); NewWindow.focus(); void(0);");             navigateToURL(refreshPage, "_self");         } // Close completeDepart function ////////////////////////////// // Code for the View res Button var viewRes:URLRequest = new URLRequest("view_res.php"); viewRES_btn.addEventListener(MouseEvent.CLICK, viewResClick); function viewResClick(event:MouseEvent):void {     navigateToURL(viewRes, "_self"); } ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // Code for the Edit Res profile Button var editRes:URLRequest = new URLRequest("edit_res.php"); editRES_btn.addEventListener(MouseEvent.CLICK, editResClick); function editResClick(event:MouseEvent):void {     navigateToURL(editRes, "_self"); } }

    this should be in the as3 forum.  but you need to return name/value pairs from your php file.

  • Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containin

    Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs. at Error$/throwError() at flash.net::URLVariables/decode() at flash.net::URLVariables() at flash.net::URLLoader/onComplete() _________________________________________________________________________________________ ____________ stop(); var DepartVars:URLVariables = new URLVariables(); var DepartURL:URLRequest = new URLRequest("scripts/www.mywebsite.com/depart.php"); DepartURL.method = URLRequestMethod.POST; DepartURL.data = DepartVars; var DepartLoader:URLLoader = new URLLoader; DepartLoader.dataFormat = URLLoaderDataFormat.VARIABLES; DepartLoader.addEventListener(Event.COMPLETE, completeDepart); depart_btn.addEventListener(MouseEvent.CLICK, DepartUser); // Function to run when the Depart button is pressed function DepartUser (event:MouseEvent):void{             // Ready the variables here for sending to PHP           DepartVars.post_code = "Depart";         // Send the data to the php file           DepartLoader.load(DepartURL);         welcome_txt.text = "Processing request...Bon Voyage"; } // Close DepartUser function /////////////////////////////////////// // Function for when the PHP file talks back to flash function completedepart(event:Event):void{     if (event.target.data.replyMsg == "success") {             var refreshPage:URLRequest = new URLRequest("javascript:NewWindow=window.location.reload(); NewWindow.focus(); void(0);");             navigateToURL(refreshPage, "_self");         } // Close completeDepart function ////////////////////////////// // Code for the View res Button var viewRes:URLRequest = new URLRequest("view_res.php"); viewRES_btn.addEventListener(MouseEvent.CLICK, viewResClick); function viewResClick(event:MouseEvent):void {     navigateToURL(viewRes, "_self"); } ///////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// // Code for the Edit Res profile Button var editRes:URLRequest = new URLRequest("edit_res.php"); editRES_btn.addEventListener(MouseEvent.CLICK, editResClick); function editResClick(event:MouseEvent):void {     navigateToURL(editRes, "_self"); } }

    I have a similar problem
    whey I use .txt my code works, but when I change to .dat external file, it get error 1067
    my code:
    import flash.display.Sprite;
    import flash.events.*;
    import flash.net.URLLoader;
    import flash.net.URLLoaderDataFormat;
    import flash.net.URLRequest;
    var loader: URLLoader = new URLLoader();
    loader.dataFormat = URLLoaderDataFormat.VARIABLES;
    loader.addEventListener(Event.COMPLETE, loading);
    loader.load(new URLRequest("rssnews.dat"));
    function loading(e: Event): void {
              news_1.text = trace(e.target.data.titulo);
              news_2.text = trace(e.target.data.texto);

  • To check that string contains space

    Hi...
    I have one char string, If that string contains any space then I want to display a message.
    how to check that string contains 'space'.
    Regards,
    Rohit

    Hi, you can do a small work.
    you can split the char string into substrings at spaces.
    if there is space then it will be splitted and then you can check the sy-subrc.
    if sy-subrc = 0,
    then the char string had some space in it.
    regards
    jayati

  • How to convert Java string into XML one?

    With SAX I can parse an xml file, but I should create xml file by hands.
    Ok, it's simple, but how to encode java string into XML constant
    like "Hello & goodby" into "Hello & goodby" ?
    Is there a standard method for such special xml characters?

    If you are creating your XML "by hand" then just make sure your hands know that you have to do that. It isn't difficult to write a Java method to do it, if "by hand" means "in Java code". Otherwise your XML is not well-formed. And as far as I know there is no package that takes ill-formed XML and fixes it up.

  • How to extract an element value from a String of HTML

    I have a web service that returns a fragment of HTML that contains a number in a table. The return parameter type is a string. I need to get this number and use it in a BPEL while loop, as the condition for the loop (while the number > 0).
    I have tried using the function bpws:getVariableData() but the BPEL PM faults and says: XPath expression failed to execute. Error while processing xpath expression. I think this is because I am trying to apply an XPath expression over a String variable.
    The return value from my web service looks like this:
    <whileConditionResultSet>
    <part xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" name="response">
    <ns1:string_Response xmlns:ns1="http://systinet.com/xsd/SchemaTypes/"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="d:string">
         <p>SQL Query: select count(*) from delta_manages</p>
         <p><table border='1'>
              <tr> <th bgcolor='#C0C0C0'>COUNT(*)</th></tr>
              <tr> <td>28</td></tr>
              </table>
         </p></ns1:string_Response>
    </part>
    </whileConditionResultSet>
    How do I get the value from the HTML table into a BPEL variable?

    the doSqlService() which executes an arbitrary SQL statement, returns a string of HTML like this:
    <doSqlServiceResponse>
    <part xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" name="response">
    <ns1:string_Response xmlns:ns1="http://systinet.com/xsd/SchemaTypes/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="d:string"><p>SQL Query: select count(*) from delta_manages</p> <p><table border='1'> <tr> <th bgcolor='#C0C0C0'>COUNT(*)</th></tr> <tr> <td>14</td></tr> </table></p></ns1:string_Response>
    </part>
    I then copy the result to the whileResultString variable
    <variable name="whileResultString" type="xsd:string"/>
    <copy>
                                       <from variable="doSqlServiceResponse" part="response" query="/ns1:string_Response">
                                       </from>
                                       <to variable="whileResultString"/>
                                  </copy>
    I realise too, a root element will be needed. This is not a mission critical problem as we could change the web service at the other end. It was originally designed for a client to display the results rather than use them within a business process. Anyway, I'm just interested to know if I can create a node from this string data in BPEL.
    Ross.

Maybe you are looking for

  • I purchased my Adobe Photoshop (6) a long time ago. Is there anything that I can do to my computer or the disc to install and run it on a Windows 7 operating system?

    I have installed it from the disc many times on every new machine that I have gotten and Adobe helps me with updating. But now I can't install it on the 7 operating system and the oldest installer that I can download from Adobe is for Shop 7. Does an

  • Unable to create Adobe PDF

    I have started receiving failures when trying to make PDF files. The failure I receive say"Unable to find Adobe PDF resource files. Do you want to run the installer in repair mode? Y/N" This condition has just started. I have uninstalled/re-installed

  • Issue with recorder

    hi all, i am encountering a strange issue. i m trying to post transaction FBRA (Reset cleared items). when i run the transaction normally, supplying the doc. no. , comp code and fiscal year...i click on save and a popup message comes up which asks to

  • How do you make an MF4770 all in one printer print?

    I just got an MF 4770 and all I see is copy, fax and scan on the front. How do I get it to print? Also, how do I choose a printer when I don't see an icon in the dock?  Where do I choose it from. I have already dowloaded and installed the two drivers

  • 12.1.2 on eDelivery

    Hi All! I would like to install and test EBS 12.1.2 but I cannot find it as download on edelivery. Only 12.1.1 is available there... Where can I get a complete installation package? Thanks, Konrad