Ejemplo n.º 1
0
 /**
  * Converts an XML document to a string. From Zaz Gmy on this StackOverflow post:
  * http://stackoverflow.com/questions/10356258/how-do-i-convert-a-org-w3c-dom-document-object-to-a-string
  *
  * @param doc The document to convert to a String.
  */
 private static String getStringFromDocument(Document doc) {
   try {
     DOMSource domSource = new DOMSource(doc);
     StringWriter writer = new StringWriter();
     StreamResult result = new StreamResult(writer);
     TransformerFactory tf = TransformerFactory.newInstance();
     Transformer transformer = tf.newTransformer();
     transformer.transform(domSource, result);
     return writer.toString();
   } catch (TransformerException ex) {
     ex.printStackTrace();
     return null;
   }
 }
 /**
  * Writes an XML file from a Document object.
  *
  * @param doc the Document object to be written to file
  * @param file the file to be written
  * @throws IOException
  * @author Klaus Meffert
  * @since 2.0
  */
 public static void writeFile(Document doc, File file) throws IOException {
   // Use a Transformer for output
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer;
   try {
     transformer = tFactory.newTransformer();
   } catch (TransformerConfigurationException tex) {
     throw new IOException(tex.getMessage());
   }
   DOMSource source = new DOMSource(doc);
   FileOutputStream fos = new FileOutputStream(file);
   StreamResult result = new StreamResult(fos);
   try {
     transformer.transform(source, result);
     fos.close();
   } catch (TransformerException tex) {
     throw new IOException(tex.getMessage());
   }
 }
Ejemplo n.º 3
0
  public static boolean writeXML(File file, Document document) {

    javax.xml.transform.Transformer transformer = null;
    try {
      transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
      return false;
    }

    transformer.setOutputProperty("indent", "yes");
    transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "2");
    transformer.setOutputProperty("encoding", "UTF-8");

    try {
      transformer.transform(new DOMSource(document), new StreamResult(file));
    } catch (TransformerException e) {
      e.printStackTrace();
      return false;
    }

    return true;
  }