Example usage for javax.xml.transform OutputKeys INDENT

List of usage examples for javax.xml.transform OutputKeys INDENT

Introduction

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

Prototype

String INDENT

To view the source code for javax.xml.transform OutputKeys INDENT.

Click Source Link

Document

indent = "yes" | "no".

Usage

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

private static void printXml(String tag, String xml, String headString) {
    if (TextUtils.isEmpty(tag)) {
        tag = TAG;//from ww  w .  j  a 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:de.uzk.hki.da.metadata.MetadataStructure.java

public void toEDM(HashMap<String, HashMap<String, List<String>>> indexInfo, File file,
        PreservationSystem preservationSystem, String objectID, String urn) {
    try {/*w  w w.j a  va  2 s.  c om*/
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        Document edmDoc = docBuilder.newDocument();
        Element rootElement = edmDoc.createElement("rdf:RDF");
        edmDoc.appendChild(rootElement);

        addXmlNsToEDM(edmDoc, rootElement);

        for (String id : indexInfo.keySet()) {
            logger.debug("Index information about " + id + ": " + indexInfo.get(id));
            Element providedCHO = addEdmProvidedCHOtoEdm(preservationSystem, id, edmDoc, rootElement);
            Element aggregation = addOreAggregationToEdm(preservationSystem, id, edmDoc, rootElement);

            if (indexInfo.get(id).get(C.EDM_IS_PART_OF) == null) {
                List<String> root = new ArrayList<String>();
                root.add("is root element");
                indexInfo.get(id).put(C.EDM_HAS_TYPE, root);
            }

            if (indexInfo.get(id).get(C.EDM_IDENTIFIER) == null) {
                List<String> IDs = new ArrayList<String>();
                IDs.add(objectID);
                IDs.add(urn);
                indexInfo.get(id).put(C.EDM_IDENTIFIER, IDs);
            } else {
                indexInfo.get(id).get(C.EDM_IDENTIFIER).add(objectID);
                indexInfo.get(id).get(C.EDM_IDENTIFIER).add(urn);
            }

            for (String elementName : indexInfo.get(id).keySet()) {
                Element parentNode = null;
                if (elementName.startsWith("dc:") || elementName.startsWith("dcterms:")
                        || elementName.equals(C.EDM_HAS_TYPE)) {
                    parentNode = providedCHO;
                } else if (elementName.startsWith("edm:")) {
                    parentNode = aggregation;
                }
                if (parentNode != null) {
                    List<String> values = indexInfo.get(id).get(elementName);
                    for (String currentValue : values) {
                        if (!currentValue.equals("")) {
                            addNewElementToParent(preservationSystem, id, elementName, currentValue, parentNode,
                                    edmDoc);
                        }
                    }
                }
            }
        }

        javax.xml.transform.Source source = new javax.xml.transform.dom.DOMSource(edmDoc);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        Result result = new javax.xml.transform.stream.StreamResult(file);
        transformer.transform(source, result);

    } catch (Exception e) {
        logger.error("Unable to create the edm file!");
        throw new RuntimeException(e);
    }

}

From source file:org.getwheat.harvest.library.dom.DomHelper.java

/**
 * Converts the {@link Document} to a string.
 * /*w  w  w .  j a v  a 2  s  .  com*/
 * @param document
 * @return XML string
 * @throws TransformerException
 */
public String convertToString(final Document document) throws TransformerException {
    final TransformerFactory factory = TransformerFactory.newInstance();
    final Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    final StringWriter writer = new StringWriter();
    final StreamResult result = new StreamResult(writer);
    final DOMSource source = new DOMSource(document);
    transformer.transform(source, result);
    return writer.toString();
}

From source file:ac.uk.diamond.sample.HttpClientTest.Utils.java

static String xmlToString(Element doc) {
    StringWriter sw = new StringWriter();
    try {/*from www .  j  a  v a 2s .  c  om*/
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        transformer.transform(new DOMSource(doc), new StreamResult(sw));
        return sw.toString();
    } catch (TransformerException e) {
        LOG.error("Unable to print message contents: ", e);
        return "<ERROR: " + e.getMessage() + ">";
    }
}

From source file:cz.cas.lib.proarc.common.export.cejsh.CejshBuilder.java

public CejshBuilder(CejshConfig config)
        throws TransformerConfigurationException, ParserConfigurationException, XPathExpressionException {
    this.gcalendar = new GregorianCalendar(UTC);
    this.logLevel = config.getLogLevel();
    TransformerFactory xslFactory = TransformerFactory.newInstance();
    tranformationErrorHandler = new TransformErrorListener();
    bwmetaXsl = xslFactory.newTransformer(new StreamSource(config.getCejshXslUrl()));
    if (bwmetaXsl == null) {
        throw new TransformerConfigurationException("Cannot load XSL: " + config.getCejshXslUrl());
    }/*w w w .  j ava2 s. c  om*/
    bwmetaXsl.setOutputProperty(OutputKeys.INDENT, "yes");
    bwmetaXsl.setErrorListener(tranformationErrorHandler);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    db = dbf.newDocumentBuilder();
    XPathFactory xPathFactory = ProarcXmlUtils.defaultXPathFactory();
    XPath xpath = xPathFactory.newXPath();
    xpath.setNamespaceContext(new SimpleNamespaceContext().add("m", ModsConstants.NS));
    issnPath = xpath.compile("m:mods/m:identifier[@type='issn' and not(@invalid)]");
    partNumberPath = xpath.compile("m:mods/m:titleInfo/m:partNumber");
    dateIssuedPath = xpath.compile("m:mods/m:originInfo/m:dateIssued");
    reviewedArticlePath = xpath.compile("m:mods/m:genre[text()='article' and @type='peer-reviewed']");
}

From source file:com.c4om.utils.xmlutils.JavaXMLUtils.java

/**
 * Method that prints a W3C {@link Document} object to a provided {@link OutputStream}. 
 * Encoding should be correctly specified.
 * @param document the document to convert
 * @param os the output stream to print to
 * @param indent whether lines must be indented or not
 * @param omitDeclaration whether the XML declaration should be omitted or not. 
 * @param encoding the encoding placed at the XML declaration and used to encode the file.
 * @return the {@link String} representation of the document
 * @throws TransformerException if there are problems during the conversion
 */// w  w w.  ja va 2  s. c o  m
public static void printW3CDocumentToOutputStream(Document document, OutputStream os, boolean indent,
        boolean omitDeclaration, String encoding) throws TransformerException {
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitDeclaration ? "yes" : "no");
    transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");
    XmlStreamWriter writer;
    if (encoding != null) {
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        writer = new XmlStreamWriter(os, encoding);
    } else {
        writer = new XmlStreamWriter(os);
    }
    StreamResult streamResult = new StreamResult(writer);
    transformer.transform(new DOMSource(document), streamResult);
}

From source file:com.wavemaker.tools.pws.install.PwsInstall.java

public static void insertEntryKey(File xmlFile, File[] runtimeJarFiles, File[] toolsJarFiles,
        String partnerName) throws Exception {
    String content = getTrimmedXML(xmlFile);

    String fromStr1 = "<!DOCTYPE";
    String toStr1 = "<!--!DOCTYPE";
    content = content.replace(fromStr1, toStr1);

    String fromStr2 = "spring-beans-2.0.dtd\">";
    String toStr2 = "spring-beans-2.0.dtd\"-->";
    content = content.replace(fromStr2, toStr2);

    FileUtils.writeStringToFile(xmlFile, content, "UTF-8");

    InputStream is = new FileInputStream(xmlFile);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);/*from  www .j a  v  a  2  s . co m*/
    DocumentBuilder docBuilder = dbf.newDocumentBuilder();
    Document doc = docBuilder.parse(is);

    insertEntryKey(doc, runtimeJarFiles, toolsJarFiles, partnerName);

    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    t.setOutputProperty(OutputKeys.INDENT, "yes");
    t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    t.transform(new DOMSource(doc), new StreamResult(xmlFile));

    content = FileUtils.readFileToString(xmlFile, "UTF-8");
    content = content.replace(toStr1, fromStr1);

    content = content.replace(toStr2, fromStr2);

    FileUtils.writeStringToFile(xmlFile, content, "UTF-8");
}

From source file:com.omertron.traileraddictapi.tools.DOMHelper.java

/**
 * Write the Document out to a file using nice formatting
 *
 * @param doc The document to save//from ww w .j av  a  2 s  . com
 * @param localFile The file to write to
 * @return
 */
public static boolean writeDocumentToFile(Document doc, String localFile) {
    try {
        TransformerFactory transfact = TransformerFactory.newInstance();
        Transformer trans = transfact.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, YES);
        trans.setOutputProperty(OutputKeys.INDENT, YES);
        trans.transform(new DOMSource(doc), new StreamResult(new File(localFile)));
        return true;
    } catch (TransformerConfigurationException ex) {
        LOG.warn(ERROR_WRITING_DOC, localFile, ex);
        return false;
    } catch (TransformerException ex) {
        LOG.warn(ERROR_WRITING_DOC, localFile, ex);
        return false;
    }
}

From source file:ca.nines.ise.util.XMLDriver.java

/**
 * Serialize an Element into a string containing XML.
 *
 * @param element//www. ja va2  s.c  om
 * @return String
 * @throws TransformerConfigurationException
 * @throws TransformerException
 * @throws UnsupportedEncodingException
 */
public String serialize(Element element)
        throws TransformerConfigurationException, TransformerException, UnsupportedEncodingException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "no");
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    DOMSource source = new DOMSource(element);
    StreamResult stream = new StreamResult(out);
    transformer.transform(source, stream);
    return new String(out.toByteArray(), "UTF-8");
}

From source file:curam.molsa.test.customfunctions.MOLSADOMReader.java

/**
 * This method is to transform the XML node to a string.
 * //  w  ww . j a  v  a 2s .co  m
 * @param node
 * @return buffer
 */
public static String toString(final Node node) {

    try {
        final TransformerFactory transFactory = TransformerFactory.newInstance();
        final Transformer transformer = transFactory.newTransformer();
        final StringWriter buffer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(buffer));
        return buffer.toString();
    } catch (final TransformerException e) {
        e.printStackTrace();
    }
    return "";
}