1

I'm creating an application for Android. My goal here is to save data to an XML file. I could use a class like Document and then save it to the file. But, my question is, could I write the XML myself?

Here's an example of the data that could be written:

class Data {
    public String[] names;
    public int age;
}

It could be saved like this:

PrintWriter pw = ...; // Get a PrintWriter
pw.println("<data>");
pw.println("<names>");
for (int i = 0; i < data.names.length; i++){
    pw.println("<name>" + data.names[i] + "</name>");
}
pw.println("</names>");
pw.println("<age>" + age + "</age>");
pw.println("</data>");
pw.close();

This would output well-formed and readable XML, it just could have invalid characters in the Strings (which could of course be changed to entities or removed). My real data is more complicated (it has 2-dimensional arrays and more data), but it could still be written like this.

I have found ways to write a Document to a file, like this one, but I'd like to do it simply without playing with Documents. Would it be bad practice to just print the XML yourself?

Community
  • 1
  • 1
PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58
  • Yes, it's bad practice. Android has many classes which deal with XML. Your code is more obscure, more prone to bugs, harder to maintain and less easy to adapt if you do it yourself. Why not use the classes provided rather than reinvent the wheel? Compare your example with listing 11 here http://www.ibm.com/developerworks/library/x-android/ – Simon Sep 07 '13 at 09:45

0 Answers0