到目前为止,我在我的 Android 应用程序中使用DOMSource将 XML 文件转换为字符串。
这是我的代码:
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 ,此代码开始抛出 OutOfMemoryError。
其背后的原因可能是什么以及如何纠正这个问题?