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

冷暖自知 提交于 2021-01-27 07:50:33

问题


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?


回答1:


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();
}


来源:https://stackoverflow.com/questions/30461474/how-to-get-the-full-content-of-an-xml-file-as-a-string-using-xmlstreamreader

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