title: Transform XML with XSLT in Java using DOM
body: <p>I've been looking around everywhere for Java samples to transform an XML document with an XSLT. I've found several samples using <code>new File("path/to/file.xml")</code> to load in the XML and the XSLT and those work great. My problem is that I'm trying to use this in a new method that will accept two <code>org.w3c.dom.Document</code> objects. As soon as I replace the <code>StreamSource</code> used to load in the XSLT with a <code>DOMSource</code> the result of my call is then the XSLT instead of the transformed XML.</p>
  
  <p>Working code from <a href="https://stackoverflow.com/questions/1915810/how-to-call-xsl-template-from-java-code">How to call XSL template from java code?</a>:</p>
  
  <pre><code>Source xmlInput = new StreamSource(new File("c:/path/to/input.xml"));
  Source xsl = new StreamSource(new File("c:/path/to/file.xsl"));
  Result xmlOutput = new StreamResult(new File("c:/path/to/output.xml"));
  
  try {
      Transformer transformer =     TransformerFactory.newInstance().newTransformer(xsl);
      transformer.transform(xmlInput, xmlOutput);
  } catch (TransformerException e) {
      // Handle.
  }
  </code></pre>
  
  <p>My code:</p>
  
  <pre><code>public static Document transformXML(Document xml, Document xslt) throws TransformerException, UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException, FactoryConfigurationError{
  
      Source xmlSource = new DOMSource(xml);
      Source xsltSource = new DOMSource(xslt);
      StreamResult result = new StreamResult(new StringWriter());
  
      // the factory pattern supports different XSLT processors
      TransformerFactory transFact =
              TransformerFactory.newInstance();
      Transformer trans = transFact.newTransformer(xsltSource);
  
      trans.transform(xmlSource, result);
  
      Document resultDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(result.getWriter().toString().getBytes("utf-8")));
  
      return resultDoc;
  }
  </code></pre>
  
  <p>My result document is then the XSLT instead of the XML. What am I doing wrong with the <code>DOMSource</code>?</p>