title: How to convert XML (String) to a valid document?
body: <p>I have XML as a string and i want to convert it to DOM document in order to parse it using XPath, i use this code to convert one String element to DOM element:</p>
  
  <pre><code>public Element convert(String xml) throws ParserConfigurationException, SAXException, IOException{
  
          Element sXml =  DocumentBuilderFactory
                  .newInstance()
                  .newDocumentBuilder()
                  .parse(new ByteArrayInputStream(xml.getBytes()))
                  .getDocumentElement();
  
  
          return  sXml;
  
      } 
  </code></pre>
  
  <p>but what if i want to convert a whole XML file?? i tried casting but it didn't work as you can't convert from Element to a Document(Exception thrown):</p>
  
  <p><strong>The Exception :</strong></p>
  
  <pre><code>Exception in thread "main" java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementImpl cannot be cast to org.w3c.dom.Document
  </code></pre>
  
  <p><strong>The Code :</strong></p>
  
  <pre><code>public Document convert(String xml) throws ParserConfigurationException, SAXException, IOException{
  
          Element sXml =  DocumentBuilderFactory
                  .newInstance()
                  .newDocumentBuilder()
                  .parse(new ByteArrayInputStream(xml.getBytes()))
                  .getDocumentElement();
  
  
          return (Document) sXml;
  
      } 
  </code></pre>
  
  <p>i also tried this but didn't work:</p>
  
  <pre><code>public Document convert(String xml) throws ParserConfigurationException, SAXException, IOException{
  
          Document sXml =  DocumentBuilderFactory
                  .newInstance()
                  .newDocumentBuilder()
                  .parse(new ByteArrayInputStream(xml.getBytes()));
  
  
          return  sXml;
  
      } 
  </code></pre>
  
  <p>what can i do to fix this problem? and if there is a way in XPath to parse a String rather than a document it also will be fine.</p>