MalcomTucker
MalcomTucker

Reputation: 7477

How to encode XML on Android?

I need to encode an XML document into a format that will pass through an XML parser as a string (i.e. strip tags). I then need to decode it back again and I need to do this on Android. What is the library/class in the Android API that I'm looking for?

Thanks

Upvotes: 3

Views: 7822

Answers (4)

Alek86
Alek86

Reputation: 1569

this question is one of the first results, when I searched the solution to this problem, so I answer here

Html.fromHtml(String)

Upvotes: 0

MalcomTucker
MalcomTucker

Reputation: 7477

I ended up using URLEncoder/URLDecoder, which seems to work nicely.

String encoded = URLEncoder.encode(xml);

Upvotes: 2

Walter Mundt
Walter Mundt

Reputation: 25271

XmlSerializer is probably what you want. Use it to build the "outer" XML document; you can give its text(...) method an intact XML string and it will do the escaping for you. You can do the same kind of thing with the DOM API by using setTextContent if you really want to build a DOM tree and then dump that to XML. As you appear to be aware, any XML parser will properly decode the entity references when you ask for the text back.

If you really want to write your own XML-building code, you might try pulling in the Apache commons-lang library into your project for it's StringEscapeUtils class. I'm not aware of anything that will just do the entity substitution without building real XML in the base Android API.

For an example, try this:

XmlSerializer xs = Xml.newSerializer();
StringWriter sw = new StringWriter();
xs.setOutput(sw);
xs.startDocument(null, null);
xs.startTag(null, "foo");
xs.text("<bar>this is some complete XML document you had around before</bar>");
xs.endTag(null, "foo");
xs.endDocument();
Log.v("XMLTest", "Generated XML = " + sw.toString());

Upvotes: 4

Patrick Kafka
Patrick Kafka

Reputation: 9892

The general Java XML Parser is the way to go.

and if you have to build it up manually you can use the XmlSerializer

edit:

Here is an article about working with xml on android, but It uses the XmlSerializer for the writing also

Upvotes: 0

Related Questions