Пример #1
2
  public static void writeXmlFile(Document doc, File saveFile, boolean systemOut) {
    try {

      Source source = new DOMSource(doc);
      Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.setParameter(OutputKeys.INDENT, "yes");
      xformer.setOutputProperty(OutputKeys.INDENT, "yes");
      xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

      if (saveFile != null) {
        Result result = new StreamResult(saveFile);
        xformer.transform(source, result);
      }

      Writer outputWriter = new StringWriter();
      Result stringOut = new StreamResult(outputWriter);
      xformer.transform(source, stringOut);

      //            new SinglePanelPopup(new TextAreaPane(outputWriter.toString()));

      if (systemOut) {
        Result system = new StreamResult(System.out);
        xformer.transform(source, system);
      }

    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    }
  }
Пример #2
0
 private InputStream getInputStream(Source source) throws Exception {
   Transformer trans = TransformerFactory.newInstance().newTransformer();
   ByteArrayBuffer bab = new ByteArrayBuffer();
   StreamResult result = new StreamResult(bab);
   trans.transform(source, result);
   return bab.newInputStream();
 }
Пример #3
0
  public void saveToXml(String fileName)
      throws ParserConfigurationException, FileNotFoundException, TransformerException,
          TransformerConfigurationException {
    System.out.println("Saving network topology to file " + fileName);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document doc = parser.newDocument();

    Element root = doc.createElement("neuralNetwork");
    root.setAttribute("dateOfExport", new Date().toString());
    Element layers = doc.createElement("structure");
    layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers()));

    for (int il = 0; il < this.numberOfLayers(); il++) {
      Element layer = doc.createElement("layer");
      layer.setAttribute("index", Integer.toString(il));
      layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons()));

      for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) {
        Element neuron = doc.createElement("neuron");
        neuron.setAttribute("index", Integer.toString(in));
        neuron.setAttribute(
            "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs()));
        neuron.setAttribute(
            "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold));

        for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) {
          Element input = doc.createElement("input");
          input.setAttribute("index", Integer.toString(ii));
          input.setAttribute(
              "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight));

          neuron.appendChild(input);
        }

        layer.appendChild(neuron);
      }

      layers.appendChild(layer);
    }

    root.appendChild(layers);
    doc.appendChild(root);

    // save
    File xmlOutputFile = new File(fileName);
    FileOutputStream fos;
    Transformer transformer;

    fos = new FileOutputStream(xmlOutputFile);
    // Use a Transformer for output
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(fos);
    // transform source into result will do save
    transformer.setOutputProperty("encoding", "iso-8859-2");
    transformer.setOutputProperty("indent", "yes");
    transformer.transform(source, result);
  }
  /**
   * Transforms the given XML string using the XSL string.
   *
   * @param xmlString The String containg the XML to transform
   * @param xslString The XML Stylesheet String containing the transform instructions
   * @return String representation of the transformation
   */
  public static String transform(String xmlString, String xslString) {

    String shortString = new String(xmlString);
    if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "...";

    try {

      TransformerFactory tFactory = TransformerFactory.newInstance();

      logger.logComment("Transforming string: " + shortString);

      StreamSource xslFileSource = new StreamSource(new StringReader(xslString));

      Transformer transformer = tFactory.newTransformer(xslFileSource);

      StringWriter writer = new StringWriter();

      transformer.transform(
          new StreamSource(new StringReader(xmlString)), new StreamResult(writer));

      String shortResult = writer.toString();
      if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "...";

      logger.logComment("Result: " + shortResult);

      return writer.toString();
    } catch (TransformerException e) {
      GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null);
      return null;
    }
  }
  /**
   * Transforms the given XML file using the specified XSL file.
   *
   * @param origXmlFile The file containg the XML to transform
   * @param xslString The XML Stylesheet conntaining the transform instructions
   * @return String representation of the transformation
   */
  public static String transform(File origXmlFile, String xslString) {
    if (!origXmlFile.exists()) {
      GuiUtils.showErrorMessage(
          logger, "Warning, XML file: " + origXmlFile + " doesn't exist", null, null);
      return null;
    }

    try {

      TransformerFactory tFactory = TransformerFactory.newInstance();

      StreamSource xslFileSource = new StreamSource(new StringReader(xslString));

      Transformer transformer = tFactory.newTransformer(xslFileSource);

      StringWriter writer = new StringWriter();

      transformer.transform(new StreamSource(origXmlFile), new StreamResult(writer));

      return writer.toString();
    } catch (Exception e) {
      GuiUtils.showErrorMessage(logger, "Error when loading the XML file: " + origXmlFile, e, null);
      return null;
    }
  }
  /**
   * Method adds a new Spring bean definition to the XML application context file.
   *
   * @param project
   * @param jaxbElement
   */
  public void addBeanDefinition(File configFile, Project project, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream());
      xsltSource.setSystemId("add-bean");
      xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

      // create transformer
      Transformer transformer = transformerFactory.newTransformer(xsltSource);
      transformer.setParameter(
          "bean_content",
          getXmlContent(jaxbElement)
              .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

      // transform
      StringResult result = new StringResult();
      transformer.transform(xmlSource, result);
      FileUtils.writeToFile(
          format(result.toString(), project.getSettings().getTabSize()), configFile);
      return;
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
  /**
   * Method removes a Spring bean definition from the XML application context file. Bean definition
   * is identified by its id or bean name.
   *
   * @param project
   * @param id
   */
  public void removeBeanDefinition(File configFile, Project project, String id) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream());
      xsltSource.setSystemId("delete-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      for (File file : configFiles) {
        xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

        // create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_id", id);

        // transform
        StringResult result = new StringResult();
        transformer.transform(xmlSource, result);
        FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
        return;
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
  /**
   * Marshal jaxb element and try to perform basic formatting like namespace clean up and attribute
   * formatting with xsl transformation.
   *
   * @param jaxbElement
   * @return
   */
  private String getXmlContent(Object jaxbElement) {
    StringResult jaxbContent = new StringResult();

    springBeanMarshaller.marshal(jaxbElement, jaxbContent);

    Source xsltSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/format-bean.xsl").getInputStream());
      Transformer transformer = transformerFactory.newTransformer(xsltSource);

      // transform
      StringResult result = new StringResult();
      transformer.transform(new StringSource(jaxbContent.toString()), result);

      if (log.isDebugEnabled()) {
        log.debug("Created bean definition:\n" + result.toString());
      }

      return result.toString();
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Пример #9
0
  /** Transform a SAX Source to a TinyTree. */
  public static DocumentInfo readTinyTree(
      Configuration configuration, Source source, boolean handleXInclude) {
    final TinyBuilder treeBuilder = new TinyBuilder();
    try {
      if (handleXInclude) {
        // Insert XIncludeContentHandler
        final TransformerXMLReceiver identityHandler = getIdentityTransformerHandler(configuration);
        identityHandler.setResult(treeBuilder);
        final XMLReceiver receiver =
            new XIncludeProcessor.XIncludeXMLReceiver(
                null,
                identityHandler,
                null,
                new TransformerURIResolver(XMLUtils.ParserConfiguration.PLAIN));
        TransformerUtils.sourceToSAX(source, receiver);
      } else {
        final Transformer identity = getIdentityTransformer(configuration);
        identity.transform(source, treeBuilder);
      }

    } catch (TransformerException e) {
      throw new OXFException(e);
    }
    return (DocumentInfo) treeBuilder.getCurrentRoot();
  }
Пример #10
0
 private void soapMessage(String path, String wsName, String wsPortName) {
   try {
     URL wsdlURL = new URL(APP_SERVER + path);
     final String NS = AbstractServiceImpl.WS_TARGET_NAMESPACE;
     Service service = Service.create(wsdlURL, new QName(NS, wsName));
     Dispatch<Source> dispatcher =
         service.createDispatch(new QName(NS, wsPortName), Source.class, Service.Mode.PAYLOAD);
     Source request = new StreamSource(new StringReader("<hello/>"));
     Source response = dispatcher.invoke(request);
     assertNotNull(response);
     Transformer transformer = TransformerFactory.newInstance().newTransformer();
     final StringWriter writer = new StringWriter();
     Result output = new StreamResult(writer);
     transformer.transform(response, output);
     Message message = new Message("clientMessages");
     message.dumpFormattedMessage(
         EchoServiceClient.class, Message.LevelEnum.INFO, "receivedAnswer", writer.toString());
   } catch (MalformedURLException e) {
     e.printStackTrace();
     fail(String.valueOf(e));
   } catch (TransformerConfigurationException e) {
     e.printStackTrace();
   } catch (TransformerException e) {
     e.printStackTrace();
   }
 }
Пример #11
0
  private String importXMI(File sourceFile)
      throws FileNotFoundException, TransformerConfigurationException, TransformerException {

    BufferedReader styledata;
    StreamSource sourcedata;
    Templates stylesheet;
    Transformer trans;

    // Get the stylesheet file stream

    styledata =
        new BufferedReader(
            new FileReader(
                new File(
                    getClass().getClassLoader().getResource("verifier/xmi2lem.xsl").getFile())));
    sourcedata = new StreamSource(new FileReader(sourceFile));

    // Initialize Saxon
    TransformerFactory factory = TransformerFactoryImpl.newInstance();
    stylesheet = factory.newTemplates(new StreamSource(styledata));

    // Apply the transformation
    trans = stylesheet.newTransformer();
    StringWriter sw = new StringWriter();
    trans.transform(sourcedata, new StreamResult(sw));

    // return sw.toString();
    return sw.getBuffer().substring(sw.getBuffer().indexOf("model"));
  }
Пример #12
0
    @Override
    public void go(Source input) throws IOException, ServletException {
      // Set the content-type for the output
      assignContentType(this.getTransformCtx());

      Transformer trans;
      try {
        trans = this.getCompiled().newTransformer();
      } catch (TransformerConfigurationException ex) {
        throw new ServletException(ex);
      }

      // Populate any params which might have been set
      if (this.getTransformCtx().getTransformParams() != null)
        populateParams(trans, this.getTransformCtx().getTransformParams());

      Result res;
      if (this.getNext().isLast())
        res = new StreamResult(this.getNext().getResponse().getOutputStream());
      else res = new SAXResult(this.getNext().getSAXHandler());

      try {
        trans.transform(input, res);
      } catch (TransformerException ex) {
        throw new ServletException(ex);
      }

      this.getNext().done();
    }
Пример #13
0
    @SuppressWarnings("unchecked")
    MutatingSnapshot(ObjVector<E> vec, Transformer<E, T> transformer) {
      E[] d = (E[]) vec.data;
      int size = vec.size;
      int len = 0;

      // --- get number of non-null elements
      for (int i = 0; i < size; i++) {
        if (d[i] != null) {
          len++;
        }
      }

      // --- allocate data
      T[] values = (T[]) new Object[len];
      int[] indices = new int[len];

      // --- fill it
      int j = 0;
      for (int i = 0; j < len; i++) {
        if (d[i] != null) {
          indices[j] = i;
          values[j] = transformer.transform(d[i]);
          j++;
        }
      }

      this.values = values;
      this.indices = indices;
    }
Пример #14
0
  /**
   * Write the XML document to the file trace.xml from
   * http://java.developpez.com/faq/xml/?page=xslt#creerXmlDom
   */
  public boolean close() {
    boolean status = true;
    try {
      // Create the DOM source
      Source source = new DOMSource(m_document);

      // Create the output file
      File file = new File(m_fileName);
      Result resultat = new StreamResult(m_fileName);

      // Create the transformer
      TransformerFactory fabrique = TransformerFactory.newInstance();
      Transformer transformer = fabrique.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

      // Transformation
      transformer.transform(source, resultat);
    } catch (Exception e) {
      System.out.println("Error creating the file trace.xml");
      status = false;
      e.printStackTrace();
    }
    return status;
  }
Пример #15
0
  public static String format(String xmlStr) { // Instantiate transformer input
    Source xmlInput = new StreamSource(new StringReader(xmlStr));
    StreamResult xmlOutput = new StreamResult(new StringWriter());

    // Configure transformer
    Transformer transformer;
    try {
      transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e) {
      logger.error(e.getMessage(), e);
      return xmlStr;
    } catch (TransformerFactoryConfigurationError e) {
      // TODO Auto-generated catch block
      logger.error(e.getMessage(), e);
      return xmlStr;
    } // An identity transformer

    try {
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      transformer.transform(xmlInput, xmlOutput);
    } catch (TransformerException e) {
      logger.error(e.getMessage(), e);
      return xmlStr;
    }

    return xmlOutput.getWriter().toString();
  }
Пример #16
0
  public synchronized void transform(File inputFile, OutputStream outputStream)
      throws TransformerException {
    ByteArrayInputStream byteArrayInputStream;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    step1.transform(new StreamSource(inputFile), new StreamResult(byteArrayOutputStream));

    byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
    byteArrayOutputStream = new ByteArrayOutputStream();

    step2.transform(
        new StreamSource(byteArrayInputStream), new StreamResult(byteArrayOutputStream));

    byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());

    step3.transform(new StreamSource(byteArrayInputStream), new StreamResult(outputStream));
  }
Пример #17
0
 private DOMSource toDOMSource(Source source) throws Exception {
   if (source instanceof DOMSource) {
     return (DOMSource) source;
   }
   Transformer trans = TransformerFactory.newInstance().newTransformer();
   DOMResult result = new DOMResult();
   trans.transform(source, result);
   return new DOMSource(result.getNode());
 }
Пример #18
0
  /**
   * Transforms a DOM Document into a file on disk
   *
   * @param fromDocument the Document to use as the source
   * @param toPath the destination file path represented as a String
   * @throws java.io.IOException
   * @throws javax.xml.transform.TransformerException
   */
  public static void transform(Document fromDocument, File toPath)
      throws TransformerException, IOException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    DOMSource source = new DOMSource(fromDocument);
    StreamResult result = new StreamResult(new BufferedWriter(new FileWriter(toPath)));
    transformer.transform(source, result);
  }
Пример #19
0
 /** Transform a SAX source to SAX events. */
 private static void sourceToSAX(Source source, ContentHandler contentHandler) {
   try {
     final Transformer identity = getIdentityTransformer();
     final SAXResult saxResult = new SAXResult(contentHandler);
     identity.transform(source, saxResult);
   } catch (TransformerException e) {
     throw new OXFException(e);
   }
 }
Пример #20
0
 public static List transform(Collection paramCollection, .Transformer paramTransformer)
 {
   ArrayList localArrayList = new ArrayList(paramCollection.size());
   Iterator localIterator = paramCollection.iterator();
   while (localIterator.hasNext()) {
     localArrayList.add(paramTransformer.transform(localIterator.next()));
   }
   return localArrayList;
 }
Пример #21
0
  public void testTransform() {
    Transformer transformer = new XslTransformer();
    assertNull(transformer.transform(null, new Transformation[0]));

    URL modelUrl = XslTransformerTest.class.getResource("model.xml");
    assertNotNull(modelUrl);
    URL transformation1Uri = XslTransformerTest.class.getResource("transformation1.xsl");
    assertNotNull(transformation1Uri);
    URL transformation2Uri = XslTransformerTest.class.getResource("transformation2.xsl");
    assertNotNull(transformation2Uri);
    Transformation transformation1 = new Transformation();
    transformation1.setUri(transformation1Uri.toString());
    Transformation transformation2 = new Transformation();
    transformation2.setUri(transformation2Uri.toString());
    Transformation[] transformations = {transformation1, transformation2};
    InputStream stream = transformer.transform(modelUrl.toString(), transformations);
    assertNotNull(stream);
  }
Пример #22
0
 /**
  * Process and compare the files which a located in different folders.
  *
  * @param sourceFolder folder where the source files are located.
  * @param targetFolder folder where the target files are located.
  * @param fileFilter filter used to select files to process.
  * @param toTargetFileName {@link Transformer} used to identify the target file name based on
  *     source file name.
  * @param preProcessor {@link ResourcePreProcessor} used to process the source files.
  * @throws IOException
  */
 private static void compareFromDifferentFolders(
     final File sourceFolder,
     final File targetFolder,
     final IOFileFilter fileFilter,
     final Transformer<String> toTargetFileName,
     final ResourcePreProcessor preProcessor)
     throws IOException {
   LOG.debug("sourceFolder: {}", sourceFolder);
   LOG.debug("targetFolder: {}", targetFolder);
   final Collection<File> files =
       FileUtils.listFiles(sourceFolder, fileFilter, FalseFileFilter.INSTANCE);
   int processedNumber = 0;
   // TODO use WroUtil#runInParallel for running tests faster
   for (final File file : files) {
     File targetFile = null;
     try {
       targetFile = new File(targetFolder, toTargetFileName.transform(file.getName()));
       final InputStream targetFileStream = new FileInputStream(targetFile);
       LOG.debug("=========== processing: {} ===========", file.getName());
       // ResourceType doesn't matter here
       compare(
           new FileInputStream(file),
           targetFileStream,
           new ResourcePostProcessor() {
             public void process(final Reader reader, final Writer writer) throws IOException {
               // ResourceType doesn't matter here
               ResourceType resourceType = ResourceType.JS;
               try {
                 resourceType = ResourceType.get(FilenameUtils.getExtension(file.getPath()));
               } catch (final IllegalArgumentException e) {
                 LOG.warn(
                     "unkown resource type for file: {}, assuming resource type is: {}",
                     file.getPath(),
                     resourceType);
               }
               try {
                 preProcessor.process(
                     Resource.create("file:" + file.getPath(), resourceType), reader, writer);
               } catch (IOException e) {
                 LOG.error("processing failed...", e);
                 throw new WroRuntimeException("Processing failed...", e);
               }
             }
           });
       processedNumber++;
     } catch (final IOException e) {
       LOG.warn(
           "Skip comparison because couldn't find the TARGET file "
               + targetFile.getPath()
               + "\n. Original exception: "
               + e.getCause());
     } catch (final Exception e) {
       throw new WroRuntimeException("A problem during transformation occured", e);
     }
   }
   logSuccess(processedNumber);
 }
Пример #23
0
  /**
   * Transforms a DOM Document into a String
   *
   * @param fromDocument the Document to use as the source
   * @return the XML as a String
   * @throws java.io.IOException
   * @throws javax.xml.transform.TransformerException
   */
  public static String transform(Document fromDocument) throws TransformerException, IOException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(fromDocument);
    transformer.transform(source, result);
    return sw.toString();
  }
Пример #24
0
 /** Transform a SAX source to SAX events. */
 public static void sourceToSAX(Source source, XMLReceiver xmlReceiver) {
   try {
     final Transformer identity = getIdentityTransformer();
     final SAXResult saxResult = new SAXResult(xmlReceiver);
     saxResult.setLexicalHandler(xmlReceiver);
     identity.transform(source, saxResult);
   } catch (TransformerException e) {
     throw new OXFException(e);
   }
 }
Пример #25
0
 /** Transform a dom4j document to a String. */
 public static String dom4jToString(Document document) {
   try {
     final Transformer identity = getXMLIdentityTransformer();
     final StringBuilderWriter writer = new StringBuilderWriter();
     identity.transform(new LocationDocumentSource(document), new StreamResult(writer));
     return writer.toString();
   } catch (TransformerException e) {
     throw new OXFException(e);
   }
 }
Пример #26
0
 /** Transform a TinyTree to a String. */
 public static String tinyTreeToString(NodeInfo nodeInfo) {
   try {
     final Transformer identity = getXMLIdentityTransformer();
     final StringBuilderWriter writer = new StringBuilderWriter();
     identity.transform(nodeInfo, new StreamResult(writer));
     return writer.toString();
   } catch (TransformerException e) {
     throw new OXFException(e);
   }
 }
Пример #27
0
 /**
  * Transform a dom4j document into a W3C DOM document
  *
  * @param document dom4j document
  * @return W3C DOM document
  * @throws TransformerException
  */
 public static org.w3c.dom.Document dom4jToDomDocument(Document document)
     throws TransformerException {
   final Transformer identity = getIdentityTransformer();
   final DOMResult domResult = new DOMResult();
   identity.transform(new DocumentSource(document), domResult);
   final Node resultNode = domResult.getNode();
   return (resultNode instanceof org.w3c.dom.Document)
       ? ((org.w3c.dom.Document) resultNode)
       : resultNode.getOwnerDocument();
 }
Пример #28
0
  public static String transform(File fromPath) throws TransformerException, IOException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    Reader reader = bomCheck(fromPath);

    StringWriter sw = new StringWriter();
    transformer.transform(new StreamSource(reader), new StreamResult(sw));
    return sw.toString();
  }
Пример #29
0
  /**
   * Transforms a DOM Document into a String
   *
   * @param fromDocument the Document to use as the source
   * @param omitXmlDeclaration will not write the XML header if true
   * @return the XML as a String
   * @throws java.io.IOException
   * @throws javax.xml.transform.TransformerException
   */
  public static String transform(Document fromDocument, boolean omitXmlDeclaration)
      throws TransformerException, IOException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    if (omitXmlDeclaration) transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(fromDocument), new StreamResult(sw));
    return sw.toString();
  }
Пример #30
0
 /** Transform a dom4j Document into a TinyTree. */
 public static DocumentInfo dom4jToTinyTree(Configuration configuration, Document document) {
   final TinyBuilder treeBuilder = new TinyBuilder();
   try {
     final Transformer identity = getIdentityTransformer(configuration);
     identity.transform(new LocationDocumentSource(document), treeBuilder);
   } catch (TransformerException e) {
     throw new OXFException(e);
   }
   return (DocumentInfo) treeBuilder.getCurrentRoot();
 }