XML Node to String Conversion for Large Sized XML

一世执手 提交于 2019-12-23 18:24:20

问题


Till now I was using DOMSource to transform the XML file into string, in my Android App.

Here's my 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; 
}

This was working fine for small xml files.

But for large sized xml this code started throwing OutOfMemoryError.

What may be the reason behind it and how to rectify this problem?


回答1:


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.

One improvement to your current code would be to change the line

transformer.setOutputProperty(OutputKeys.INDENT, "yes");

to

transformer.setOutputProperty(OutputKeys.INDENT, "no");

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.



来源:https://stackoverflow.com/questions/15897562/xml-node-to-string-conversion-for-large-sized-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!