5

I'm in a part of an application where I have an access to the XmlStreamReader which is representing the XML file needed to be fully read into a String.

Is there a way to obtain the XML content without building another XmlStreamReader or using another stream on the file?

Lii
  • 11,553
  • 8
  • 64
  • 88
M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72

1 Answers1

11
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;

private String getOuterXml(XMLStreamReader xmlr) throws TransformerConfigurationException,
    TransformerFactoryConfigurationError, TransformerException
{
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new StAXSource(xmlr), new StreamResult(stringWriter));
    return stringWriter.toString();
}
Alex
  • 865
  • 13
  • 24
  • Is there a better way to achieve this ? We are using the same method but a 20 MB file is getting exploded to 400MB using this conversion. Incase there is a better solution it will be helpful. – Ashish Kathait Nov 18 '21 at 04:41