XML节点至字符串转换为大型XML [英] XML Node to String Conversion for Large Sized XML
问题描述
到现在为止我所用的 DOMSource的以XML文件转换为字符串,在我的Android应用程序。
Till now I was using DOMSource to transform the XML file into string, in my Android App.
这里是我的code
public String convertElementToString (Node element) throws TransformerConfigurationException, TransformerFactoryConfigurationError
{
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(element);
try {
transformer.transform(source, result);
}
catch (TransformerException e) {
Log.e("CONVERT_ELEMENT_TO_STRING", "converting element to string failed. Aborting", e);
}
String xmlString = result.getWriter().toString();
xmlString = xmlString.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
xmlString = xmlString.replace("\n", "");
return xmlString;
}
本是工作的罚款对小XML 文件。
但是为大型XML 这code开始的抛出的OutOfMemoryError
But for large sized xml this code started throwing OutOfMemoryError.
这可能是它背后的原因如何纠正这个问题?
What may be the reason behind it and how to rectify this problem?
推荐答案
第一关:如果您只需要XML作为字符串,并且不使用节点
为别的,你应该使用的StAX(流API为XML ),而不是作为具有低得多的内存占用。你会在 javax.xml.stream中
封装标准库找到StAX的。
First off: if you just need the XML as a string, and aren't using the Node
for anything else, you should use StAX (Streaming API for XML) instead, as that has a much lower memory footprint. You'll find StAX in the javax.xml.stream
package of the standard libraries.
一个改进到当前code将更改行
One improvement to your current code would be to change the line
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
到
transformer.setOutputProperty(OutputKeys.INDENT, "no");
既然你在方法的啦去除换行,这不是非常有用索取更多缩进输出。这是一个很小的事情,但是如果有很多的标签(因此,换行和空格进行缩进)在你的XML可能会降低内存需求了一下。
Since you're stripping newlines anyway at the end of the method, it's not very useful to request additional indentation in the output. It's a small thing, but might reduce your memory requirements a bit if there are a lot of tags (hence, newlines and whitespace for indentation) in your XML.
这篇关于XML节点至字符串转换为大型XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!