Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Java Development

Reply
Contributor
Posts: 48
Registered: ‎07-10-2010
My Device: 8300

Encode a String

How can i encode  a string value .

I'm sending  a data in xml  in the HTTP Post .

for example

<deviceName>Blackberry</deviceName>

this works fine.

 

But now if i do the below it fails

<deviceName><<&Black</deviceName>

 

Developer
Posts: 4,764
Registered: ‎07-21-2008
My Device: Not Specified

Re: Encode a String

The ampersand '&' has to be encoded like

 

&amp;

 

The '<' like

 

&lt;

 

These are standard HTML character entities

 

See this article:

 

http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references

 

 

 

 

Contributor
Posts: 48
Registered: ‎07-10-2010
My Device: 8300

Re: Encode a String

Exactly, but do i have to explicitly write the code for each char.

Isnt there a  predefined method or api available?

Developer
Posts: 1,305
Registered: ‎01-21-2009
My Device: Not Specified

Re: Encode a String

I don't think there's a class that escapes a String for XML, but there is a way to do what you want. The steps are:

  1. Build a DOM representation of the XML you want to send back to the server.
  2. Create and configure an XMLWriter that writes to a ByteArrayOutputStream.
  3. Call DOMInternalRepresentation.parse(doc, writer). This will generate the properly escaped byte sequence in the ByteArrayOutputStream, which you can then send to the server.

The only hard part of this is building the DOM representation. You can use a DocumentBuilder to create an empty Document, then use the Document methods to create and add all the nodes of the DOM that you need.




Solved? click "Accept as solution". Helpful? give kudos by clicking on the star.
New Contributor
Posts: 2
Registered: ‎12-14-2011
My Device: Developer
My Carrier: Dev

Re: Encode a String

I have done just that. However I have trouble setting an encoding for the Document. I know the API allows getXMLEncoding(), but there is no call for setting it. Is there a way to do this?

Thanks,

Iulia