Home > Tutorials > Android XML Adventure – Create & Write XML Data

Android XML Adventure – Create & Write XML Data


Article Series: Android XML Adventure

Author: Pete Houston (aka. `xjaphx`)

TABLE OF CONTENTS

  1. What is the “Thing” called XML?
  2. Parsing XML Data w/ SAXParser
  3. Parsing XML Data w/ DOMParser
  4. Parsing XML Data w/ XMLPullParser
  5. Create & Write XML Data
  6. Compare: XML Parsers
  7. Parsing XML using XPath
  8. Parsing HTML using HtmlCleaner
  9. Parsing HTML using JSoup
  10. Sample Project 1: RSS Parser – using SAXParser
  11. Sample Project 1: RSS Parser – using DOM Parser
  12. Sample Project 1: RSS Parser – using XMLPullParser
  13. Sample Project 2: HTML Parser – using HtmlCleaner
  14. Sample Project 2: HTML Parser – using JSoup
  15. Finalization on the “Thing” called XML!

=========================================

Have you mastered with parsing XML stuffs well?

Today, I’d like to talk about writing XML file, just like a normal Java program, there’s no differences.

Our steps are going to be:

+ First, create XML string (which is residing in memory for later use).

+ Second, write the XML string to a file, which belongs to internal storage of an Android application.

About the second step, I assume that you’ve already known how to do it. Shortly, `Context.openFileOutput()` will do the job.

For the first thing, there various ways to do; however, I’d like to introduce only most three common ways.

1. A normal String format

Understand what I mean?

	public static String writeUsingNormalOperation(Study study) {
		String format =
				"<?xml version='1.0' encoding='UTF-8'?>" +
				"<record>" +
				"	<study id='%d'>" +
				"		<topic>%s</topic>" +
				"		<content>%s</content>" +
				"		<author>%s</author>" +
				"		<date>%s</date>" +
				"	</study>" +
				"</record>";
		return String.format(format, study.mId, study.mTopic, study.mContent, study.mAuthor, study.mDate);
	}

The Good:

  • Very quick and easy.
  • Not much code or custom objects required.

The Bad:

  • Straightforwardly static string, if you want to output a list of XML tags, this way doesn’t work.
  • Easy to make mistake while making the format for output.

2. Using DOM

	public static String writeUsingDOM(Study study) throws Exception {
		Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		// create root: <record>
		Element root = doc.createElement(Study.RECORD);
		doc.appendChild(root);

		// create: <study>
		Element tagStudy = doc.createElement(Study.STUDY);
		root.appendChild(tagStudy);
		// add attr: id =
		tagStudy.setAttribute(Study.ID, String.valueOf(study.mId));

		// create: <topic>
		Element tagTopic = doc.createElement(Study.TOPIC);
		tagStudy.appendChild(tagTopic);
		tagTopic.setTextContent(study.mTopic);

		// create: <content>
		Element tagContent = doc.createElement(Study.CONTENT);
		tagStudy.appendChild(tagContent);
		tagContent.setTextContent(study.mContent);

		// create: <author>
		Element tagAuthor = doc.createElement(Study.AUTHOR);
		tagStudy.appendChild(tagAuthor);
		tagAuthor.setTextContent(study.mAuthor);

		// create: <date>
		Element tagDate = doc.createElement(Study.DATE);
		tagStudy.appendChild(tagDate);
		tagDate.setTextContent(study.mDate);

		// create Transformer object
		Transformer transformer = TransformerFactory.newInstance().newTransformer();
		StringWriter writer = new StringWriter();
		StreamResult result = new StreamResult(writer);
		transformer.transform(new DOMSource(doc), result);

		// return XML string
		return writer.toString();
	}

The Good:

  • Implementable for dynamic data output.
  • Flexible XML configuration.

The Bad:

  • Too much object creations, using a lot.
  • Performance gets worse if XML document is large.

3. Using XMLSerializer

	public static String writeUsingXMLSerializer(Study study) throws Exception {
		XmlSerializer xmlSerializer = Xml.newSerializer();
		StringWriter writer = new StringWriter();

		xmlSerializer.setOutput(writer);
		// start DOCUMENT
		xmlSerializer.startDocument("UTF-8", true);
		// open tag: <record>
		xmlSerializer.startTag("", Study.RECORD);
		// open tag: <study>
		xmlSerializer.startTag("", Study.STUDY);
		xmlSerializer.attribute("", Study.ID, String.valueOf(study.mId));

		// open tag: <topic>
		xmlSerializer.startTag("", Study.TOPIC);
		xmlSerializer.text(study.mTopic);
		// close tag: </topic>
		xmlSerializer.endTag("", Study.TOPIC);

		// open tag: <content>
		xmlSerializer.startTag("", Study.CONTENT);
		xmlSerializer.text(study.mContent);
		// close tag: </content>
		xmlSerializer.endTag("", Study.CONTENT);

		// open tag: <author>
		xmlSerializer.startTag("", Study.AUTHOR);
		xmlSerializer.text(study.mAuthor);
		// close tag: </author>
		xmlSerializer.endTag("", Study.AUTHOR);

		// open tag: <date>
		xmlSerializer.startTag("", Study.DATE);
		xmlSerializer.text(study.mDate);
		// close tag: </date>
		xmlSerializer.endTag("", Study.DATE);

		// close tag: </study>
		xmlSerializer.endTag("", Study.STUDY);
		// close tag: </record>
		xmlSerializer.endTag("", Study.RECORD);

		// end DOCUMENT
		xmlSerializer.endDocument();

		return writer.toString();
	}

The Good:

  • Not like DOM, it requires only at least two objects to create XML document.
  • The syntax is so damn easy to work with.
  • The performance is pretty good.

The Bad:

  • At this point, I’ve not faced any drawback of using this.

4. Simple Framework

Homepage: http://simple.sourceforge.net/

This is an amazing XML Serialization/De-serialization, it is really easy to use and having quite good performance on XML data structure.

However, I’m not going to talk about it here, so you might want to discover about it yourselves. Or maybe, I will give a quick look over this framework in another article.

Well, it’s end for today post, and happy learning!

Be await for the next article on the series.

Cheers,

Pete Houston

  1. July 22, 2016 at 4:15 pm

    How one could write unit tests to be sure that generation is working correctly. Let’s say I am using XmlSerializer (Variant 3 in your post). How to test that string is correctly generated xml

  2. September 15, 2013 at 3:40 am

    Hi there to every one, it’s genuinely a good for me to visit this web site, it
    contains priceless Information.

  3. July 31, 2013 at 12:17 am

    When someone writes an paragraph he/she retains the image
    of a user in his/her mind that how a user can be
    aware of it. Thus that’s why this piece of writing is perfect.
    Thanks!

  4. Primoz
    April 25, 2013 at 3:24 pm

    Great examples! Thanks!

  5. Tubakagan
    September 11, 2012 at 4:12 am

    Hi,

    I create and write XML file , but I want to add tag in xml file .How can I do this ?

  6. Sheraz Amin
    December 30, 2011 at 1:01 pm

    Hi,
    I want to write create and write XML file on SDcard , I am doing this using XMLSerializer with your help,I am little confused where I have to create XML and then write into it on your code.I am begginer and that is my first app.Thanx

  7. ghouse
    December 20, 2011 at 5:12 pm

    Hi,

    i want to know what the empty spaces in the below code

    xmlSerializer.startTag(“”, Study.RECORD);

    i am new to this environment please explain that one.

    • April 23, 2018 at 11:41 am

      Its a string parameter that is blank, a quick search on XmlSerializer.startTag method will tell you what parameters it takes and most likely other overloaded signatures for the startTag method. Looking up XmlSeralizer’s methods wouldnt be bad idea if u wanna learn more then whats gven here.

      Very nice tut credit given 🏆+1

  1. No trackbacks yet.

Leave a comment