code: public static XMLStreamWriter getXMLStreamWriter(XMLOutputFactory factory, Result result) throws XMLStreamException
      {
          XMLStreamWriter xmlStreamWriter;
  
          if (result instanceof SAXResult) {
              // SAXResult is not supported by the standard XMLOutputFactory
              xmlStreamWriter =
                  new XMLEventStreamWriter(new SAXEventWriter(((SAXResult) result).getHandler()), XML_EVENT_FACTORY);
          } else if (result instanceof StAXResult) {
              // XMLEventWriter is not supported as result of XMLOutputFactory#createXMLStreamWriter
              StAXResult staxResult = (StAXResult) result;
              if (staxResult.getXMLStreamWriter() != null) {
                  xmlStreamWriter = staxResult.getXMLStreamWriter();
              } else {
                  xmlStreamWriter = new XMLEventStreamWriter(staxResult.getXMLEventWriter(), XML_EVENT_FACTORY);
              }
          } else {
              xmlStreamWriter = factory.createXMLStreamWriter(result);
          }
  
          return xmlStreamWriter;
      }
docs: Extract or create an instance of {@link XMLStreamWriter} from the provided {@link Result}.
  
  @param factory the {@link XMLOutputFactory} to use (if needed)
  @param result the result
  @return the {@link XMLStreamWriter}
  @throws XMLStreamException when failing to extract xml stream writer
  @since 9.5.2
  @since 9.6RC1