Can anybody tell me how to convert a string to an xml file in android?
Thanks
Can anybody tell me how to convert a string to an xml file in android?
Thanks
The safest method is this:
Document doc = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(
new InputSource(
new StringReader(string)
)
);
Some people say you should close the StringReader, but that doesn't have any practical benefit in this case.
There is another solution using ByteArrayInputStream:
Document doc = DocumentBuilderFactory
.newInstance()
.newDocumentBuilder()
.parse(
new ByteArrayInputStream(
string.getBytes("UTF-8")
)
);
Make sure you explicitly specify encoding when using string.getBytes, otherwise it uses the system default encoding, which could change depending on what platform you are running. Seems like UTF-8 is what the parse method wants, but it's not in the docs.
If the application is simple and doesn't need too much xml manipulation performance then DOM should do the trick. Otherwise try using SAX which can give a big boost in performance in certain occasions. Look at this tutorial that explains well the differences between them.