【发布时间】:2010-10-11 13:38:20
【问题描述】:
谁能告诉我如何在android中将字符串转换为xml文件?
谢谢
【问题讨论】:
-
字符串是否已经是 XML 格式并且您想创建一个内存对象?还是要将字符串作为完整 XML 文档的一部分输出?
-
是的字符串已经在 xml 中。我想成为一个 xml 文档
谁能告诉我如何在android中将字符串转换为xml文件?
谢谢
【问题讨论】:
最安全的方法是这样的:
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。
【讨论】:
使用DOM。
【讨论】:
如果应用程序很简单并且不需要太多的 xml 操作性能,那么 DOM 应该可以解决问题。否则,请尝试使用 SAX,它可以在某些情况下大大提高性能。查看this 教程,它很好地解释了它们之间的差异。
【讨论】: