Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the full content of an XML file as a String using XmlStreamReader?

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?

like image 857
M. A. Kishawy Avatar asked May 26 '15 14:05

M. A. Kishawy


1 Answers

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();
}
like image 76
Alex Avatar answered Nov 14 '22 23:11

Alex