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 String
s (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 Document
s. Would it be bad practice to just print the XML yourself?