Example usage for javax.xml.transform Transformer setOutputProperty

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

Introduction

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

Prototype

public abstract void setOutputProperty(String name, String value) throws IllegalArgumentException;

Source Link

Document

Set an output property that will be in effect for the transformation.

Usage

From source file:com.sitewhere.configuration.ConfigurationMigrationSupport.java

/**
 * Format the given XML document./*from www.ja v  a2 s. c o m*/
 * 
 * @param xml
 * @return
 * @throws SiteWhereException
 */
public static String format(Document xml) throws SiteWhereException {
    try {
        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");
        tf.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        Writer out = new StringWriter();
        tf.transform(new DOMSource(xml), new StreamResult(out));
        return out.toString();
    } catch (Exception e) {
        throw new SiteWhereException("Unable to format XML document.", e);
    }
}

From source file:com.casewaresa.framework.util.LegacyJasperInputStream.java

public static String addDocTypeAndConvertDOMToString(final Document document) {

    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = null;
    try {/*from w ww  .jav a2s.c o m*/
        trans = transfac.newTransformer();
    } catch (TransformerConfigurationException ex) {
        log.error(ex.getMessage(), ex);
    }

    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "//JasperReports//DTD Report Design//EN");
    trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
            "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd");

    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(document);
    try {
        trans.transform(source, result);
    } catch (TransformerException ex) {
        log.error(ex.getMessage(), ex);
    }

    return sw.toString();
}

From source file:Main.java

public static String toString(Node node) {
    final Transformer identityTransformer;
    try {//from  ww w . ja  va 2 s.co  m
        identityTransformer = transformerFactory.newTransformer();
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException("Failed to create identity transformer to serialize Node to String", e);
    }
    identityTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    final StringWriter outputWriter = new StringWriter();
    final StreamResult outputTarget = new StreamResult(outputWriter);
    final DOMSource xmlSource = new DOMSource(node);
    try {
        identityTransformer.transform(xmlSource, outputTarget);
    } catch (TransformerException e) {
        throw new RuntimeException("Failed to convert Node to String using Transformer", e);
    }

    return outputWriter.toString();
}

From source file:apiconnector.TestDataFunctionality.java

public static String toPrettyString(String xml, int indent) throws Exception {
    // Turn xml string into a document
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8"))));

    // Remove whitespaces outside tags
    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
            XPathConstants.NODESET);

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        node.getParentNode().removeChild(node);
    }/* w  w  w  .j av a 2 s.  co m*/

    // Setup pretty print options
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", indent);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    // Return pretty print xml string
    StringWriter stringWriter = new StringWriter();
    transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
    return stringWriter.toString();
}

From source file:Main.java

public static String nodeToString(final Node node, final boolean omitXMLDecl) {
    final StringWriter writer = new StringWriter();
    final Transformer transformer;
    try {/*from   w w w  .ja  v a  2 s . c om*/
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (final TransformerException e) {
        throw new AssertionError("No errors expected when creating an identity transformer", e);
    }

    if (omitXMLDecl) {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    } else {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    }

    try {
        transformer.transform(new DOMSource(node), new StreamResult(writer));
    } catch (final TransformerException e) {
        throw new AssertionError("No errors expected during identity transformation", e);
    }

    return writer.toString();
}

From source file:Main.java

/**
 * Adds a new node to a file.// w w  w.jav a 2 s.  c o  m
 *
 * @param nodeType {@link String} The type of the element to add.
 * @param idField {@link String} The name of the field used to identify this
 * node.
 * @param nodeID {@link String} The identifier for this node, so its data
 * can be later retrieved and modified.
 * @param destFile {@link File} The file where the node must be added.
 * @param attributes {@link ArrayList} of array of String. The arrays must
 * be bidimensional (first index must contain attribute name, second one
 * attribute value). Otherwise, an error will be thrown. However, if
 * <value>null</value>, it is ignored.
 */
public static void addNode(String nodeType, String idField, String nodeID, File destFile,
        ArrayList<String[]> attributes) {
    if (attributes != null) {
        for (Iterator<String[]> it = attributes.iterator(); it.hasNext();) {
            if (it.next().length != 2) {
                throw new IllegalArgumentException("Invalid attribute combination");
            }
        }
    }
    /*
     * XML DATA CREATION - BEGINNING
     */
    DocumentBuilder docBuilder;
    Document doc;
    try {
        docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        doc = docBuilder.parse(destFile);
    } catch (SAXException | IOException | ParserConfigurationException ex) {
        return;
    }

    Node index = doc.getFirstChild(), newElement = doc.createElement(nodeType);
    NamedNodeMap elementAttributes = newElement.getAttributes();

    Attr attrID = doc.createAttribute(idField);
    attrID.setValue(nodeID);
    elementAttributes.setNamedItem(attrID);

    if (attributes != null) {
        for (Iterator<String[]> it = attributes.iterator(); it.hasNext();) {
            String[] x = it.next();
            Attr currAttr = doc.createAttribute(x[0]);
            currAttr.setValue(x[1]);
            elementAttributes.setNamedItem(currAttr);
        }
    }

    index.appendChild(newElement);
    /*
     * XML DATA CREATION - END
     */

    /*
     * XML DATA DUMP - BEGINNING
     */
    Transformer transformer;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException ex) {
        return;
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StreamResult result = new StreamResult(new StringWriter());
    DOMSource source = new DOMSource(doc);
    try {
        transformer.transform(source, result);
    } catch (TransformerException ex) {
        return;
    }

    String xmlString = result.getWriter().toString();
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(destFile))) {
        bufferedWriter.write(xmlString);
    } catch (IOException ex) {
    }
    /*
     * XML DATA DUMP - END
     */
}

From source file:Main.java

/**
 * Write an XML document to the outputstream provided. This will use the provided Transformer.
 * //from w  w w  .  j a va 2s.  c om
 * @param transformer The transformer (can be obtained from XmlUtils.createIndentingTransformer())
 * @param outputEntry The output stream to write to.
 * @param document The document to write
 */
public static final void writeXml(Transformer transformer, OutputStream outputEntry, Document document) {
    //      Assert.notNull(transformer, "Transformer required");
    //      Assert.notNull(outputEntry, "Output entry required");
    //      Assert.notNull(document, "Document required");
    //      
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    try {
        transformer.transform(new DOMSource(document), createUnixStreamResultForEntry(outputEntry));
    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:com.sinet.gage.dlap.utils.XMLUtils.java

/**
 * @param String//  w  ww  .j ava 2 s .  com
 * @param String
 * @return String
 */
public static String parseXML(String xml, String rootElementName) {
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setValidating(false);
        DocumentBuilder db;
        db = dbf.newDocumentBuilder();
        Document newDoc = db.parse(new ByteArrayInputStream(xml.getBytes()));

        Element element = (Element) newDoc.getElementsByTagName(rootElementName).item(0);
        // Imports a node from another document to this document,
        // without altering
        Document newDoc2 = db.newDocument();
        // or removing the source node from the original document
        Node copiedNode = newDoc2.importNode(element, true);
        // Adds the node to the end of the list of children of this node
        newDoc2.appendChild(copiedNode);

        Transformer tf = TransformerFactory.newInstance().newTransformer();
        tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        tf.setOutputProperty(OutputKeys.INDENT, "yes");

        Writer out = new StringWriter();

        tf.transform(new DOMSource(newDoc2), new StreamResult(out));

        return out.toString();
    } catch (TransformerException | ParserConfigurationException | SAXException | IOException e) {
        LOGGER.error("Exception in parsing xml from response: ", e);
    }
    return "";
}

From source file:com.code19.library.L.java

private static void printXml(String tag, String xml, String headString) {
    if (TextUtils.isEmpty(tag)) {
        tag = TAG;/*  w  ww.ja v  a 2 s  . c  om*/
    }
    if (xml != null) {
        try {
            Source xmlInput = new StreamSource(new StringReader(xml));
            StreamResult xmlOutput = new StreamResult(new StringWriter());
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
            transformer.transform(xmlInput, xmlOutput);
            xml = xmlOutput.getWriter().toString().replaceFirst(">", ">\n");
        } catch (Exception e) {
            e.printStackTrace();
        }
        xml = headString + "\n" + xml;
    } else {
        xml = headString + "Log with null object";
    }

    printLine(tag, true);
    String[] lines = xml.split(LINE_SEPARATOR);
    for (String line : lines) {
        if (!TextUtils.isEmpty(line)) {
            Log.d(tag, "|" + line);
        }
    }
    printLine(tag, false);
}

From source file:XMLUtils.java

public static void writeTo(Source src, OutputStream os, int indent, String charset, String omitXmlDecl) {
    Transformer it;
    try {//from  www  .ja va 2  s.  com

        //charset = "utf-8"; 

        it = newTransformer();
        it.setOutputProperty(OutputKeys.METHOD, "xml");
        if (indent > -1) {
            it.setOutputProperty(OutputKeys.INDENT, "yes");
            it.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
        }
        it.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDecl);
        it.setOutputProperty(OutputKeys.ENCODING, charset);
        it.transform(src, new StreamResult(os));
    } catch (TransformerException e) {
        throw new RuntimeException("Failed to configure TRaX", e);
    }

}