tags:

views:

55

answers:

3

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

A: 

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

sadboy
Sorry, maybe I wasn't clear, I already have a parser, I'm looking for the encoder. I just want to turn '<' into < and so on...
MalcomTucker
sorry, I misunderstood.
sadboy
A: 

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());
Walter Mundt
A: 

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

String encoded = URLEncoder.encode(xml);
MalcomTucker