【问题标题】:Convert a string to an xml file in android在android中将字符串转换为xml文件
【发布时间】:2010-10-11 13:38:20
【问题描述】:

谁能告诉我如何在android中将字符串转换为xml文件?

谢谢

【问题讨论】:

  • 字符串是否已经是 XML 格式并且您想创建一个内存对象?还是要将字符串作为完整 XML 文档的一部分输出?
  • 是的字符串已经在 xml 中。我想成为一个 xml 文档

标签: android xml string


【解决方案1】:

最安全的方法是这样的:

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 是 parse 方法想要的,but it's not in the docs。

【讨论】:

    【解决方案2】:

    使用DOM。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-06-16
        • 2011-12-27
        • 1970-01-01
        • 1970-01-01
        • 2016-02-07
        • 2011-04-22
        • 1970-01-01
        相关资源
        最近更新 更多