在android中将字符串转换为xml文件

时间:2010-10-11 13:38:21

标签: android xml string

有人能告诉我如何将字符串转换为android中的xml文件吗?

由于

3 个答案:

答案 0 :(得分:2)

最安全的方法是:

Document doc = DocumentBuilderFactory
    .newInstance()
    .newDocumentBuilder()
    .parse(
            new InputSource(
                    new StringReader(string)
            )
    );

有人说你应该关闭StringReader,but that doesn't have any practical benefit in this case

还有另一种使用ByteArrayInputStream的解决方案:

Document doc = DocumentBuilderFactory
    .newInstance()
    .newDocumentBuilder()
    .parse(
            new ByteArrayInputStream(
                    string.getBytes("UTF-8")
            )
    );

确保在使用string.getBytes,otherwise it uses the system default encoding时明确指定编码,这可能会根据您运行的平台而改变。看起来像UTF-8就是解析方法想要的,but it's not in the docs

答案 1 :(得分:0)

使用DOM

答案 2 :(得分:0)

如果应用程序很简单并且不需要太多的xml操作性能,那么DOM就应该这样做。否则尝试使用SAX,在某些情况下可以大大提高性能。查看this教程,它可以很好地解释它们之间的差异。

相关问题