2

Can anybody tell me how to convert a string to an xml file in android?

Thanks

Justin
  • 84,773
  • 49
  • 224
  • 367
mohan
  • 13,035
  • 29
  • 108
  • 178
  • Is the string already in XML format and you want to create an in-memory object? Or do you want to output a string as part of a complete XML document? – Pontus Gagge Oct 11 '10 at 13:41
  • yes string is already in xml .I want to be a xml document – mohan Oct 11 '10 at 14:31

3 Answers3

3

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.

Community
  • 1
  • 1
SharkAlley
  • 11,399
  • 5
  • 51
  • 42
0

Use the DOM.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

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.

RicardoSBA
  • 785
  • 1
  • 6
  • 18