Ignatius Tremor Ignatius Tremor - 6 months ago 44
Android Question

Is startDocument() with Androids XMLSerializer required?

For a certain application (serializing and deserializing an object for transport via XMPP PubSub item payload), I need to create XML fragments - this is I have to omit the document declaration.

I'm using the

org.xmlpull.v1.XmlSerializer
class; unfortunately there doesn't seem to be much documentation available on the correct usage of it. At least all documentation I've found on its
startDocument()
method leaves it unclear whether I can or cannot skip calling this method. At least all examples I've found call this method (but all of them explained just how to create complete XML documents, no fragments).

To give a code example:

XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter xmlStringWriter = new StringWriter();

try {
xmlSerializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
xmlSerializer.setOutput(xmlStringWriter);

// xmlSerializer.startDocument("UTF-8", true);

xmlSerializer.startTag(null, "tag-name");
// ...
xmlSerializer.endTag(null, "tag-name";

// xmlSerializer.endDocument();

xmlSerializer.flush();
} catch (IOException e) {
// Hanle exception
}
String xmlOutputString = xmlStringWriter.toString();


Is this allowed? And if not, is there any other way to generate fragments with XMLSerializer without parsing the output string in order to manually remove the document declaration (e.g. calling startDocument only with
null
parameters)?

Answer

Here comes the answer in short terms: No, calling startDocument() is not required and will skip generating the document declaration.