如何使用 XmlStreamReader 将 XML 文件的全部内容作为字符串获取?

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

我在一个应用程序的一部分,我可以访问 XmlStreamReader,它代表 XML 文件需要完全读入 String

有没有办法在不构建另一个 XmlStreamReader 或在 file 上使用另一个流的情况下获取 XML 内容?

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