Java Code Examples for javax.xml.transform.Transformer#transform()

The following examples show how to use javax.xml.transform.Transformer#transform() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ConnectorXmlUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String format(String unformattedXml, Source xslt) {
   try {
      Document doc = parseXmlFile(unformattedXml);
      DOMSource domSource = new DOMSource(doc);
      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = null;
      if (xslt != null) {
         transformer = tf.newTransformer(xslt);
      } else {
         transformer = tf.newTransformer();
      }

      transformer.setOutputProperty("indent", "yes");
      transformer.setOutputProperty("omit-xml-declaration", "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(1));
      transformer.transform(domSource, result);
      return writer.toString();
   } catch (Exception var8) {
      throw new InstantiationException(var8);
   }
}
 
Example 2
Source File: XML.java    From jpx with Apache License 2.0 6 votes vote down vote up
static Document clone(final Document doc) {
	if (doc == null) return null;

	try {
		final Transformer transformer = TFHolder.INSTANCE.factory
			.newTransformer();

		final DOMSource source = new DOMSource(doc);
		final DOMResult result = new DOMResult();
		transformer.transform(source,result);
		return (Document)result.getNode();
	} catch (TransformerException e) {
		throw (DOMException)
			new DOMException(DOMException.NOT_SUPPORTED_ERR, e.getMessage())
				.initCause(e);
	}
}
 
Example 3
Source File: AbstractBingExtractor.java    From wandora with GNU General Public License v3.0 6 votes vote down vote up
protected 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;
    }
}
 
Example 4
Source File: XPathMasker.java    From eclair with Apache License 2.0 6 votes vote down vote up
@Override
public String process(String string) {
    if (xPathExpressions.isEmpty()) {
        return string;
    }
    InputStream stream = new ByteArrayInputStream(string.getBytes());
    try {
        Document document = documentBuilderFactory.newDocumentBuilder().parse(stream);
        XPath xPath = xPathfactory.newXPath();
        for (String xPathExpression : xPathExpressions) {
            NodeList nodeList = (NodeList) xPath.compile(xPathExpression).evaluate(document, XPathConstants.NODESET);
            for (int a = 0; a < nodeList.getLength(); a++) {
                nodeList.item(a).setTextContent(replacement);
            }
        }
        StringWriter writer = new StringWriter();
        Transformer transformer = transformerFactory.newTransformer();
        for (Map.Entry<String, String> entry : outputProperties.entrySet()) {
            transformer.setOutputProperty(entry.getKey(), entry.getValue());
        }
        transformer.transform(new DOMSource(document), new StreamResult(writer));
        return writer.getBuffer().toString();
    } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException | TransformerException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 5
Source File: XmlToHtmlConverter.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public void generateIndividualCommandPages() {
    for (String commandName : allCommandNames) {

        try {

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource("generatecommands.xsl"));

            transformer.transform
            // Modify this path to the location of the input files on your system.
                    (new javax.xml.transform.stream.StreamSource("apis/" + commandName + ".xml"),
                    // Modify this path with the desired output location.
                            new javax.xml.transform.stream.StreamResult(new FileOutputStream("html/apis/" + commandName + ".html")));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 6
Source File: XMLBase.java    From neoscada with Eclipse Public License 1.0 6 votes vote down vote up
protected void storeXmlDocument ( final Document doc, final File file ) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException
{
    // create output directory

    file.getParentFile ().mkdirs ();

    // write out xml

    final TransformerFactory transformerFactory = TransformerFactory.newInstance ();

    final Transformer transformer = transformerFactory.newTransformer ();
    transformer.setOutputProperty ( OutputKeys.INDENT, "yes" ); //$NON-NLS-1$

    final DOMSource source = new DOMSource ( doc );
    final StreamResult result = new StreamResult ( file );
    transformer.transform ( source, result );
}
 
Example 7
Source File: XMLUtils.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
public void transform(Document aDocument, Writer aWriter)
		throws TransformerException {

	ApplicationPreferences thePreferences = ApplicationPreferences
			.getInstance();

	Transformer theTransformer = transformerFactory.newTransformer();
	theTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
	theTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
	theTransformer.setOutputProperty(OutputKeys.ENCODING, PlatformConfig
			.getXMLEncoding());
	theTransformer.setOutputProperty(
			"{http://xml.apache.org/xslt}indent-amount", ""
					+ thePreferences.getXmlIndentation());
	theTransformer.transform(new DOMSource(aDocument), new StreamResult(
			aWriter));
}
 
Example 8
Source File: ExternalMetadataReader.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static JavaWsdlMappingType transformAndRead(Source src, boolean disableXmlSecurity) throws TransformerException, JAXBException {
    Source xsl = new StreamSource(Util.class.getResourceAsStream(TRANSLATE_NAMESPACES_XSL));
    JAXBResult result = new JAXBResult(jaxbContext(disableXmlSecurity));
    TransformerFactory tf = XmlUtil.newTransformerFactory(!disableXmlSecurity);
    Transformer transformer = tf.newTemplates(xsl).newTransformer();
    transformer.transform(src, result);
    return getJavaWsdlMapping(result.getResult());
}
 
Example 9
Source File: XMLFileWriter.java    From Juicebox with MIT License 5 votes vote down vote up
private static void writeXML() throws TransformerException {
    DOMSource domSource = new DOMSource(xmlDoc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(domSource, streamResult);
}
 
Example 10
Source File: XPathNegativeZero.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static String xform(final String xml, final String xsl) throws Exception {
    final TransformerFactory tf = TransformerFactory.newInstance();
    final Source xslsrc = new StreamSource(new File(xsl));
    final Templates tmpl = tf.newTemplates(xslsrc);
    final Transformer t = tmpl.newTransformer();

    StringWriter writer = new StringWriter();
    final Source src = new StreamSource(new File(xml));
    final Result res = new StreamResult(writer);

    t.transform(src, res);
    return writer.toString();
}
 
Example 11
Source File: StringValuesReader.java    From android-string-extractor-plugin with MIT License 5 votes vote down vote up
private String convertNodeToText(Node node )throws TransformerException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter sw = new StringWriter();
    t.transform(new DOMSource(node), new StreamResult(sw));
    return sw.toString();
}
 
Example 12
Source File: CFDv33.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes(InputStream in) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Source source = new StreamSource(in);
    Result out = new StreamResult(baos);
    TransformerFactory factory = tf;
    if (factory == null) {
        factory = TransformerFactory.newInstance();
        factory.setURIResolver(new URIResolverImpl());
    }
    Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
    transformer.transform(source, out);
    in.close();
    return baos.toByteArray();
}
 
Example 13
Source File: CFDv2.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
byte[] getOriginalBytes() throws Exception {
    JAXBSource in = new JAXBSource(context, document);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Result out = new StreamResult(baos);
    TransformerFactory factory = tf;
    if (factory == null) {
        factory = TransformerFactory.newInstance();
        factory.setURIResolver(new URIResolverImpl());
    }
    Transformer transformer = factory.newTransformer(new StreamSource(getClass().getResourceAsStream(XSLT)));
    transformer.transform(in, out);
    return baos.toByteArray();
}
 
Example 14
Source File: ServerInterceptor.java    From careconnect-reference-implementation with Apache License 2.0 5 votes vote down vote up
private void performTransform(OutputStream os, IBaseResource resource, String styleSheet) {

        // Input xml data file
        ClassLoader classLoader = getContextClassLoader();

        // Input xsl (stylesheet) file
        String xslInput = classLoader.getResource(styleSheet).getFile();
        log.debug("xslInput = "+xslInput);
        // Set the property to use xalan processor
        System.setProperty("javax.xml.transform.TransformerFactory",
                "org.apache.xalan.processor.TransformerFactoryImpl");

        // try with resources
        try {
            InputStream xml = new ByteArrayInputStream(ctx.newXmlParser().encodeResourceToString(resource).getBytes(StandardCharsets.UTF_8));

            // For Windows repace escape sequence
            xslInput = xslInput.replace("%20"," ");
            log.debug("open fileInputStream for xsl "+xslInput);
            FileInputStream xsl = new FileInputStream(xslInput);

            // Instantiate a transformer factory
            TransformerFactory tFactory = TransformerFactory.newInstance();

            // Use the TransformerFactory to process the stylesheet source and produce a Transformer
            StreamSource styleSource = new StreamSource(xsl);
            Transformer transformer = tFactory.newTransformer(styleSource);

            // Use the transformer and perform the transformation
            StreamSource xmlSource = new StreamSource(xml);
            StreamResult result = new StreamResult(os);
            log.trace("Transforming");
            transformer.transform(xmlSource, result);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            ex.printStackTrace();
            throw new InternalErrorException(ex.getMessage());
        }

    }
 
Example 15
Source File: XMLUtil.java    From Cynthia with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 
 * @description:TODO
 * @date:2014-11-11 下午4:11:25
 * @version:v1.0
 * @param document
 * @param encode
 * @param os
 * @throws TransformerException
 */
public static void document2OutputStream(Document document, String encode, OutputStream os) throws TransformerException
{
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    DOMSource source = new DOMSource(document);
    transformer.setOutputProperty("encoding", encode);
    transformer.setOutputProperty("indent", "yes");

    transformer.transform(source, new StreamResult(os));
}
 
Example 16
Source File: TrpXPathProcessor.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
public void writeToFile(Document doc, File outFile, boolean doIndent) throws TransformerFactoryConfigurationError, TransformerException {
       Transformer transformer = TransformerFactory.newInstance().newTransformer();
      	transformer.setOutputProperty(OutputKeys.INDENT, doIndent ? "yes" : "no");
       DOMSource source = new DOMSource(doc);
       StreamResult file = new StreamResult(outFile);
       transformer.transform(source, file);
}
 
Example 17
Source File: XSLT.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws TransformerException {
    ByteArrayOutputStream resStream = new ByteArrayOutputStream();
    TransformerFactory trf = TransformerFactory.newInstance();
    Transformer tr = trf.newTransformer(new StreamSource(System.getProperty("test.src", ".") + XSLTRANSFORMER));
    tr.transform(new StreamSource(System.getProperty("test.src", ".") + XMLTOTRANSFORM), new StreamResult(resStream));
    System.out.println("Transformation completed. Result:" + resStream.toString());
    if (!resStream.toString().equals(EXPECTEDRESULT)) {
        throw new RuntimeException("Incorrect transformation result");
    }
}
 
Example 18
Source File: ConfigTests.java    From utah-parser with Apache License 2.0 5 votes vote down vote up
/**
 * Build a Reader for the document - this will contain the XML doc for the parser
 * @return the reader
 * @throws TransformerException
 */
private Reader buildDocReader() throws TransformerException {
  // use the DOM writing tools to write the XML to this document
  StringWriter writer = new StringWriter();
  TransformerFactory tFactory = TransformerFactory.newInstance();
  Transformer transformer = tFactory.newTransformer();

  DOMSource source = new DOMSource(document);
  StreamResult result = new StreamResult(writer);
  transformer.transform(source, result);

  // return this as a reader
  return new StringReader(writer.toString());
}
 
Example 19
Source File: TransformerTest.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private StringWriter transformResourceToStringWriter(Transformer transformer, String xmlResource) throws TransformerException {
    StringWriter sw = new StringWriter();
    transformer.transform(new StreamSource(getClass().getResource(xmlResource).toString()), new StreamResult(sw));
    return sw;
}
 
Example 20
Source File: SimpleCertificateReportFacade.java    From dss with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void generateHtmlReport(XmlSimpleCertificateReport simpleCertificateReport, Result result) throws IOException, TransformerException, JAXBException {
	Transformer transformer = SimpleCertificateReportXmlDefiner.getHtmlBootstrap4Templates().newTransformer();
	transformer.transform(new JAXBSource(getJAXBContext(), wrap(simpleCertificateReport)), result);
}