Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Node to String Conversion for Large Sized XML

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?

like image 295
Shail Adi Avatar asked Dec 21 '25 15:12

Shail Adi


1 Answers

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.

like image 63
markusk Avatar answered Dec 23 '25 05:12

markusk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!