Example usage for javax.xml.transform Transformer transform

List of usage examples for javax.xml.transform Transformer transform

Introduction

In this page you can find the example usage for javax.xml.transform Transformer transform.

Prototype

public abstract void transform(Source xmlSource, Result outputTarget) throws TransformerException;

Source Link

Document

Transform the XML Source to a Result.

Usage

From source file:Main.java

private static Document transformToDomResult(Document document, Transformer transformer)
        throws TransformerConfigurationException, TransformerException {
    DOMResult domResult = new DOMResult();
    synchronized (transformer) {
        transformer.transform(new DOMSource(document), domResult);
    }/* ww  w. j a  v a2s . c  o m*/
    Document transformedDocument = (Document) domResult.getNode();
    return transformedDocument;
}

From source file:Main.java

public static synchronized Object deserialize(Source source, InputStream xsltSource, Class cls)
        throws TransformerConfigurationException, JAXBException, TransformerException {
    Object obj = null;//from  ww w .j  ava  2 s . co  m
    JAXBContext jc = JAXBContext.newInstance(cls);

    if (xsltSource != null) {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        transformer = factory.newTransformer(new StreamSource(xsltSource));

        JAXBResult result = new JAXBResult(jc);
        transformer.transform(source, result);
        obj = result.getResult();
    } else {
        obj = jc.createUnmarshaller().unmarshal(source);
    }
    return obj;
}

From source file:eu.eidas.engine.test.simple.SSETestUtils.java

/**
 * Marshall.//ww  w  .jav  a  2 s .  co m
 *
 * @param samlToken the SAML token
 *
 * @return the byte[]
 *
 * @throws MarshallingException the marshalling exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws TransformerException the transformer exception
 */
public static byte[] marshall(final XMLObject samlToken)
        throws MarshallingException, ParserConfigurationException, TransformerException {

    final javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    dbf.setNamespaceAware(true);
    dbf.setIgnoringComments(true);
    final javax.xml.parsers.DocumentBuilder docBuild = dbf.newDocumentBuilder();

    // Get the marshaller factory
    final MarshallerFactory marshallerFactory = Configuration.getMarshallerFactory();

    // Get the Subject marshaller
    final Marshaller marshaller = marshallerFactory.getMarshaller(samlToken);

    final Document doc = docBuild.newDocument();

    // Marshall the SAML token
    marshaller.marshall(samlToken, doc);

    // Obtain a byte array representation of the marshalled SAML object
    final DOMSource domSource = new DOMSource(doc);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final StreamResult result = new StreamResult(new OutputStreamWriter(baos, Constants.UTF8));
    final TransformerFactory transFact = TransformerFactory.newInstance();
    final Transformer transformer = transFact.newTransformer();
    transformer.transform(domSource, result);

    return baos.toByteArray();
}

From source file:Main.java

public static String formatXmlAsStringNoWhitespace(Document document) {

    StringWriter writer = new StringWriter();
    TransformerFactory factory = TransformerFactory.newInstance();

    try {/*from  ww w  .  ja v a 2s . c  o  m*/

        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "no");
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

        transformer.transform(new DOMSource(document), new StreamResult(writer));
    } catch (TransformerException ex) {

        throw new RuntimeException("Error formatting xml as no-whitespace string", ex);
    }

    return writer.toString();
}

From source file:Main.java

/**
 * Returns a String representation of the DOM hierarchy rooted at the argument Node.
 * @param node The root Node of the DOM hierarchy to translate.
 * @return A String representation of the DOM hierarchy rooted at the
 * argument Node, or null if the operation fails.
 *///from w w w . j a  va2s  . com
public static String toXMLString(Node node, boolean header) {
    try {
        Source source = new DOMSource(node);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        if (!header)
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    } catch (TransformerException e) {
        e.printStackTrace();
    } // try - catch

    return null;
}

From source file:Main.java

public static void formatXML(Document xml, URIResolver resolver, Document xsl, Writer output) throws Exception {
    StreamResult result = new StreamResult(output);
    DOMSource xslSource = new DOMSource(xsl);
    TransformerFactory factory = TransformerFactory.newInstance();
    DOMSource xmlSource = new DOMSource(xml);
    Templates t = factory.newTemplates(xslSource);
    Transformer transformer = t.newTransformer();
    transformer.setURIResolver(resolver);
    transformer.transform(xmlSource, result);
}

From source file:Main.java

private static void save(Document doc, Result result) {
    //--- Write the XML document in XML file
    try {/*  ww w .j  av a 2  s . c  om*/
        Source source = new DOMSource(doc);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();

        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        //--- Transform the DOM document into XML file 
        transformer.transform(source, result);
    } catch (TransformerException e) {
        throw new RuntimeException("XML error : Cannot save : TransformerException", e);
    } catch (TransformerFactoryConfigurationError e) {
        throw new RuntimeException("XML error : Cannot save : TransformerFactoryConfigurationError", e);
    }
}

From source file:Main.java

public static String convertResultSetToXML(ResultSet rs)
        throws SQLException, ParserConfigurationException, TransformerException {
    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);/* ww  w .j  a v a  2s  .  c  o m*/

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            if (value != null) {
                Element node = doc.createElement(columnName.replaceAll("\\(", "_").replaceAll("\\)", "_"));
                node.appendChild(doc.createTextNode(value.toString()));
                row.appendChild(node);
            }
        }
    }

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StringWriter writer = new StringWriter();
    transformer.transform(new DOMSource(doc), new StreamResult(writer));
    String output = writer.getBuffer().toString().replaceAll("\n|\r", "");

    return output;
}

From source file:Main.java

private static String transformToStringResult(Document document, Transformer transformer)
        throws TransformerConfigurationException, TransformerException {
    StringWriter stringWriter = new StringWriter();
    synchronized (transformer) {
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
    }/*from  ww  w  . j av a  2  s  .co m*/
    return stringWriter.toString();
}

From source file:Main.java

/**
 * Method to transform an XML document into a pretty-formatted string.
 * @param xml/*from   ww  w.j a  v  a  2s .  c  om*/
 * @return
 * @throws Exception
 */
public static final String xmlToString(Document xml) throws Exception {
    Transformer tf = TransformerFactory.newInstance().newTransformer();
    tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    tf.setOutputProperty(OutputKeys.INDENT, "yes");
    Writer out = new StringWriter();
    tf.transform(new DOMSource(xml), new StreamResult(out));
    return out.toString();
}