Example usage for javax.xml.transform TransformerFactory setAttribute

List of usage examples for javax.xml.transform TransformerFactory setAttribute

Introduction

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

Prototype

public abstract void setAttribute(String name, Object value);

Source Link

Document

Allows the user to set specific attributes on the underlying implementation.

Usage

From source file:Main.java

public static String toPrettyString(String xml) {
    int indent = 4;
    try {/*from  www.j  a v a 2  s.  c  o  m*/
        // 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);
        }

        // 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, "no");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");

        // Return pretty print xml string
        StringWriter stringWriter = new StringWriter();
        transformer.transform(new DOMSource(document), new StreamResult(stringWriter));
        return stringWriter.toString();
    } catch (Exception e) {
        System.out.println(xml);
        throw new RuntimeException(
                "Problems prettyfing xml content [" + Splitter.fixedLength(100).split(xml) + "]", e);
    }
}

From source file:PayHost.Utilities.java

/**
 * Make the http post response pretty with indentation
 *
 * @param input Response/*from   ww  w  .j  a  v  a2  s  .c o m*/
 * @param indent Indentation level
 * @return String in pretty format
 */
public static String prettyFormat(String input, int indent) {
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", indent);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (IllegalArgumentException | TransformerException e) {
        throw new RuntimeException(e); // simple exception handling, please review it
    }
}

From source file:com.hangum.tadpole.engine.sql.util.export.XMLExporter.java

/**
 * make content/*from www.  java2 s. c  o m*/
 * 
 * @param tableName
 * @param rsDAO
 * @return
 */
public static String makeContent(String tableName, QueryExecuteResultDTO rsDAO, int intLimitCnt)
        throws Exception {
    final StringWriter stWriter = new StringWriter();
    final List<Map<Integer, Object>> dataList = rsDAO.getDataList().getData();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();
    final Element results = doc.createElement(tableName);
    doc.appendChild(results);

    Map<Integer, String> mapLabelName = rsDAO.getColumnLabelName();
    for (int i = 0; i < dataList.size(); i++) {
        Map<Integer, Object> mapColumns = dataList.get(i);
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int j = 1; j < mapColumns.size(); j++) {
            String columnName = mapLabelName.get(j);
            String strValue = mapColumns.get(j) == null ? "" : "" + mapColumns.get(j);

            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(strValue));
            row.appendChild(node);
        }

        if (i == intLimitCnt)
            break;
    }

    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setAttribute("indent-number", 4);

    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1");
    StreamResult sr = new StreamResult(stWriter);
    transformer.transform(domSource, sr);

    return stWriter.toString();
}

From source file:com.hangum.tadpole.engine.sql.util.export.XMLExporter.java

/**
 * make content file//  w w w .  j  av  a2 s .c  o m
 * 
 * @param tableName
 * @param rsDAO
 * @return
 * @throws Exception
 */
public static String makeContentFile(String tableName, QueryExecuteResultDTO rsDAO) throws Exception {
    String strTmpDir = PublicTadpoleDefine.TEMP_DIR + tableName + System.currentTimeMillis()
            + PublicTadpoleDefine.DIR_SEPARATOR;
    String strFile = tableName + ".xml";
    String strFullPath = strTmpDir + strFile;

    final StringWriter stWriter = new StringWriter();
    final List<Map<Integer, Object>> dataList = rsDAO.getDataList().getData();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();
    final Element results = doc.createElement(tableName);
    doc.appendChild(results);

    Map<Integer, String> mapLabelName = rsDAO.getColumnLabelName();
    for (int i = 0; i < dataList.size(); i++) {
        Map<Integer, Object> mapColumns = dataList.get(i);
        Element row = doc.createElement("Row");
        results.appendChild(row);

        for (int j = 1; j < mapColumns.size(); j++) {
            String columnName = mapLabelName.get(j);
            String strValue = mapColumns.get(j) == null ? "" : "" + mapColumns.get(j);

            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(strValue));
            row.appendChild(node);
        }
    }

    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setAttribute("indent-number", 4);

    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1");
    StreamResult sr = new StreamResult(stWriter);
    transformer.transform(domSource, sr);

    FileUtils.writeStringToFile(new File(strFullPath), stWriter.toString(), true);

    return strFullPath;
}

From source file:Main.java

/**
 * Transforms a {@link Source} object into a {@link String} representation.
 * /*from   w ww  . j ava 2 s .  c  o m*/
 * @param xml the source input.
 * @param pretty if {@code true} then pretty print with white space.
 * @param writer write the string to this {@link Writer}.
 * @throws TransformerException
 */
public static void toString(Source xml, boolean pretty, Writer writer) throws TransformerException {
    final TransformerFactory factory = TransformerFactory.newInstance();

    try {
        factory.setAttribute("{http://xml.apache.org/xalan}indent-amount", 2);
    } catch (IllegalArgumentException iae) {
        // try a different ident amount
        try {
            factory.setAttribute("indent-number", 2);
        } catch (IllegalArgumentException iae2) {
            // ignore
        }
    }

    final Transformer transformer = factory.newTransformer();
    if (pretty) {
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    }
    transformer.transform(xml, new StreamResult(writer));
}

From source file:com.petercho.Encoder.java

public static String formatXml(String xml) throws TransformerException {
    Source xmlInput = new StreamSource(new StringReader(xml));
    StringWriter stringWriter = new StringWriter();
    StreamResult xmlOutput = new StreamResult(stringWriter);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformerFactory.setAttribute("indent-number", 4);
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(xmlInput, xmlOutput);
    return xmlOutput.getWriter().toString();
}

From source file:ru.retbansk.utils.UsefulMethods.java

/**
 * For testing usage. Take unformatted xml string. Return pretty readable xml string
 * //ww  w .  j  av a2 s .c  o  m
 * @param input take unformatted xml string
 * @param indent a number of white spaces before each line
 * @return pretty readable xml string
 */

public static String prettyFormat(String input, int indent) {
    try {
        Source xmlInput = new StreamSource(new StringReader(input));
        StringWriter stringWriter = new StringWriter();
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        // This statement works with JDK 6
        transformerFactory.setAttribute("indent-number", indent);

        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);
        return xmlOutput.getWriter().toString();
    } catch (Throwable e) {
        // You'll come here if you are using JDK 1.5
        // you are getting an the following exeption
        // java.lang.IllegalArgumentException: Not supported: indent-number
        // Use this code (Set the output property in transformer.
        try {
            Source xmlInput = new StreamSource(new StringReader(input));
            StringWriter stringWriter = new StringWriter();
            StreamResult xmlOutput = new StreamResult(stringWriter);
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
            transformer.transform(xmlInput, xmlOutput);
            return xmlOutput.getWriter().toString();
        } catch (Throwable t) {
            return input;
        }
    }
}

From source file:Main.java

/**
 * Serialise the supplied W3C DOM subtree.
 *
 * @param nodeList The DOM subtree as a NodeList.
 * @param format Format the output./*www  .  j a v  a2 s  .co m*/
 * @param writer The target writer for serialization.
 * @throws DOMException Unable to serialise the DOM.
 */
public static void serialize(NodeList nodeList, boolean format, Writer writer) throws DOMException {

    if (nodeList == null) {
        throw new IllegalArgumentException("null 'subtree' NodeIterator arg in method call.");
    }

    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;

        if (format) {
            try {
                factory.setAttribute("indent-number", new Integer(4));
            } catch (Exception e) {
                // Ignore... Xalan may throw on this!!
                // We handle Xalan indentation below (yeuckkk) ...
            }
        }
        transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        if (format) {
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "4");
        }

        int listLength = nodeList.getLength();

        // Iterate through the Node List.
        for (int i = 0; i < listLength; i++) {
            Node node = nodeList.item(i);

            if (isTextNode(node)) {
                writer.write(node.getNodeValue());
            } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                writer.write(((Attr) node).getValue());
            } else if (node.getNodeType() == Node.ELEMENT_NODE) {
                transformer.transform(new DOMSource(node), new StreamResult(writer));
            }
        }
    } catch (Exception e) {
        DOMException domExcep = new DOMException(DOMException.INVALID_ACCESS_ERR,
                "Unable to serailise DOM subtree.");
        domExcep.initCause(e);
        throw domExcep;
    }
}

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);
    }/*from  ww w.ja  va2s  . c o  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:com.hangum.tadpole.engine.sql.util.QueryUtils.java

/**
 * query to xml// w  ww . j a v  a 2  s  .  com
 * 
 * @param userDB
 * @param strQuery
 * @param listParam
 */
@SuppressWarnings("deprecation")
public static String selectToXML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam)
        throws Exception {
    final StringWriter stWriter = new StringWriter();

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    final Document doc = builder.newDocument();
    final Element results = doc.createElement("Results");
    doc.appendChild(results);

    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
    QueryRunner qr = new QueryRunner(client.getDataSource());
    qr.query(strQuery, listParam.toArray(), new ResultSetHandler<Object>() {

        @Override
        public Object handle(ResultSet rs) throws SQLException {
            ResultSetMetaData metaData = rs.getMetaData();

            while (rs.next()) {
                Element row = doc.createElement("Row");
                results.appendChild(row);
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    String columnName = metaData.getColumnName(i);
                    Object value = rs.getObject(i) == null ? "" : rs.getObject(i);
                    Element node = doc.createElement(columnName);
                    node.appendChild(doc.createTextNode(value.toString()));
                    row.appendChild(node);
                }
            }

            return stWriter.toString();
        }
    });

    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    tf.setAttribute("indent-number", 4);

    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1");
    StreamResult sr = new StreamResult(stWriter);
    transformer.transform(domSource, sr);

    return stWriter.toString();
}