Example usage for javax.xml.transform OutputKeys OMIT_XML_DECLARATION

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

Introduction

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

Prototype

String OMIT_XML_DECLARATION

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

Click Source Link

Document

omit-xml-declaration = "yes" | "no".

Usage

From source file:com.meltmedia.rodimus.RodimusCli.java

public static void transformDocument(File inputFile, File outputDir, boolean verbose) throws Exception {
    StreamSource xhtmlHandlerSource = createStreamSource(RodimusCli.class.getResource("/rodimus.xsl"));

    File indexFile = new File(outputDir, "index.html");
    File assetDir = new File(outputDir, IMAGE_DIR_NAME);
    assetDir.mkdirs();//from  w w  w . jav  a2 s .  com

    // Set up the output buffer.
    StringBuilderWriter output = new StringBuilderWriter();

    // Set up the serializer.
    ToXMLStream serializer = new ToXMLStream();
    serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, String.valueOf(2));
    serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_LINE_SEPARATOR, "\n");
    serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputPropertiesFactory.S_KEY_ENTITIES, "yes");
    serializer.setOutputProperty(OutputKeys.ENCODING, "US-ASCII");
    serializer.setWriter(output);

    // Set up the xhtmlStructure handler.
    TransformerHandler xhtmlHandler = getContentHandler(xhtmlHandlerSource);
    xhtmlHandler.setResult(new SAXResult(serializer));

    // build the Tika handler.
    ParseContext context = createParseContext(assetDir, verbose);
    PostTikaHandler cleanUp = new PostTikaHandler(IMAGE_DIR_NAME);
    cleanUp.setContentHandler(xhtmlHandler);
    parseInput(createInputStream(inputFile), cleanUp, context, verbose);

    // Do some regular expression cleanup.
    String preOutput = output.toString();
    preOutput = preOutput.replaceAll("/>", " />");
    // TODO: img is in this list, but it is not a block level element.
    String blockLevel = "(?:address|article|aside|audio|blockquote|canvas|dd|div|dl|fieldset|figcaption|figure|footer|form|h[1-6]|header|hgroup|hr|noscript|ol|output|p|pre|sectop|table|tfoot|ul|video|img)";
    preOutput = preOutput.replaceAll("(</" + blockLevel + ">)(\\s*)(<" + blockLevel + ")", "$1$2$2$3");
    preOutput = "<!doctype html>\n" + preOutput;

    FileUtils.write(indexFile, preOutput, "UTF-8");

    // Clean out images dir if it's empty
    if (assetDir.list().length == 0) {
        FileUtils.deleteQuietly(assetDir);
    }
}

From source file:dk.statsbiblioteket.util.xml.DOM.java

/**
 * Convert the given DOM to an UTF-8 XML String.
 *
 * @param dom                the Document to convert.
 * @param withXmlDeclaration if trye, an XML-declaration is prepended.
 * @return the dom as an XML String.//from  w  w w.j  ava 2s  . co  m
 * @throws TransformerException if the dom could not be converted.
 */
// TODO: Consider optimizing this with ThreadLocal Transformers
public static String domToString(Node dom, boolean withXmlDeclaration) throws TransformerException {
    Transformer t = TransformerFactory.newInstance().newTransformer();
    t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    if (withXmlDeclaration) {
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    } else {
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    }
    t.setOutputProperty(OutputKeys.METHOD, "xml");

    /* Transformer */
    StringWriter sw = new StringWriter();
    t.transform(new DOMSource(dom), new StreamResult(sw));

    return sw.toString();
}

From source file:com.urbancode.x2o.xml.XmlWrite.java

public Transformer createTransformer() throws TransformerConfigurationException {
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer transformer = transFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    return transformer;
}

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

/**
 * Serialize an Element into a string containing XML.
 *
 * @param element//from www  .j  av  a 2  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:com.krawler.portal.tools.ServiceBuilder.java

public void createBusinessProcessforCRUD(String classname, String companyid) {
    try {/* ww w . j  a v a  2 s. co m*/
        DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
        Document doc = docBuilder.parse(new ClassPathResource("logic/businesslogicEx.xml").getFile());
        //Document doc = docBuilder.newDocument();
        NodeList businessrules = doc.getElementsByTagName("businessrules");
        Node businessruleNode = businessrules.item(0);
        Element processEx = doc.getElementById(classname + "_addNew");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        processEx = doc.getElementById(classname + "_delete");

        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }
        processEx = doc.getElementById(classname + "_edit");
        if (processEx != null) {
            businessruleNode.removeChild(processEx);
        }

        Element process = createBasicProcessNode(doc, classname, "createNewRecord", "_addNew", "createNew");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "deleteRecord", "_delete", "deleteRec");
        businessruleNode.appendChild(process);
        process = createBasicProcessNode(doc, classname, "editRecord", "_edit", "editRec");
        businessruleNode.appendChild(process);

        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");
        trans.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//KRAWLER//DTD BUSINESSRULES//EN");
        trans.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "http://192.168.0.4/dtds/businesslogicEx.dtd");
        trans.setOutputProperty(OutputKeys.VERSION, "1.0");
        trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

        // create string from xml tree
        File outputFile = (new ClassPathResource("logic/businesslogicEx.xml").getFile());
        outputFile.setWritable(true);
        // StringWriter sw = new StringWriter();
        StreamResult sresult = new StreamResult(outputFile);

        DOMSource source = new DOMSource(doc);
        trans.transform(source, sresult);

    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (SAXException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
    }

}

From source file:tut.pori.javadocer.Javadocer.java

/**
 * //  w  ww . j  a  v a  2 s.co m
 * @throws IllegalArgumentException
 */
public Javadocer() throws IllegalArgumentException {
    _restUri = System.getProperty(PROPERTY_REST_URI);
    if (StringUtils.isBlank(_restUri)) {
        throw new IllegalArgumentException("Bad " + PROPERTY_REST_URI);
    }

    try {
        _documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        _transformer = TransformerFactory.newInstance().newTransformer();
        _transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        _transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // because of an issue with java's transformer indent, we need to add standalone attribute 
        _transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        _transformer.setOutputProperty(OutputKeys.ENCODING, CHARSET);
        _transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        _transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    } catch (ParserConfigurationException | TransformerConfigurationException
            | TransformerFactoryConfigurationError ex) {
        LOGGER.error(ex, ex);
        throw new IllegalArgumentException("Failed to create document builder/transformer instance.");
    }

    _xPath = XPathFactory.newInstance().newXPath();
    _client = HttpClients.createDefault();
}

From source file:com.fujitsu.dc.common.utils.DcCoreUtils.java

/**
 * XML?DOM?????./*w w w  .j  a va 2  s . c  o  m*/
 * @param node ???
 * @return ???
 */
public static String nodeToString(final Node node) {
    StringWriter sw = new StringWriter();
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.transform(new DOMSource(node), new StreamResult(sw));
    } catch (TransformerException te) {
        throw new RuntimeException("nodeToString Transformer Exception", te);
    }
    return sw.toString();
}

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

/**
 * Write the Document out to a file using nice formatting
 *
 * @param doc The document to save// w w  w .j  a  v a 2s .  c o m
 * @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 + localFile, ex);
        return false;
    } catch (TransformerException ex) {
        LOG.warn(ERROR_WRITING + localFile, ex);
        return false;
    }
}

From source file:com.krawler.formbuilder.servlet.workflowHandler.java

public String exportBPELFile(HttpServletRequest request, HttpServletResponse response) {
    Writer output = null;/*from  ww w  . j a va  2 s. c om*/
    try {
        String workflow = request.getParameter("jsonnodeobj");
        String linejson = request.getParameter("linejson");
        String processId = request.getParameter("flowid");
        String containerId = request.getParameter("containerId");
        this.parentSplit = request.getParameter("parentSplit");
        String path = ConfigReader.getinstance().get("workflowpath") + processId;
        path = path + System.getProperty("file.separator") + "Export";
        File fdir = new File(path);
        if (!fdir.exists()) {
            fdir.mkdirs();
        }
        File file = new File(fdir + System.getProperty("file.separator") + "flow.bpel");
        if (file.exists()) {
            file.delete();
        }
        output = new BufferedWriter(new FileWriter(file));
        JSONObject jsonobj = new JSONObject(workflow);
        JSONObject json_line = new JSONObject(linejson);
        createDocument();
        expwritebpel(jsonobj, containerId, processId, json_line);
        TransformerFactory transfac = TransformerFactory.newInstance();
        Transformer trans1 = transfac.newTransformer();
        trans1.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans1.setOutputProperty(OutputKeys.INDENT, "yes");

        StringWriter sw = new StringWriter();
        StreamResult kwcresult = new StreamResult(sw);
        DOMSource kwcsource = new DOMSource(dom);
        trans1.transform(kwcsource, kwcresult);
        output.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        output.write("\n");
        output.write(sw.toString());

        output.close();
        return "{success:true}";
    } catch (TransformerConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (TransformerException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (ParserConfigurationException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } catch (IOException ex) {
        logger.warn(ex.getMessage(), ex);
        return "{success:true}";
    } finally {
        try {
            output.close();
        } catch (IOException ex) {
            logger.warn(ex.getMessage(), ex);
            return "{success:true}";
        }
    }

}

From source file:com.google.visualization.datasource.render.HtmlRenderer.java

/**
 * Transforms a document to a valid html string.
 *
 * @param document The document to transform
 *
 * @return A string representation of a valid html.
 *///from w ww .  j  a  v  a 2  s  . c o m
private static String transformDocumentToHtmlString(Document document) {
    // Generate a CharSequence from the xml document.
    Transformer transformer = null;
    try {
        transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e) {
        log.error("Couldn't create a transformer", e);
        throw new RuntimeException("Couldn't create a transformer. This should never happen.", e);
    }
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD HTML 4.01//EN");
    transformer.setOutputProperty(OutputKeys.METHOD, "html");
    transformer.setOutputProperty(OutputKeys.VERSION, "4.01");

    DOMSource source = new DOMSource(document);
    Writer writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    try {
        transformer.transform(source, result);
    } catch (TransformerException e) {
        log.error("Couldn't transform", e);
        throw new RuntimeException("Couldn't transform. This should never happen.", e);
    }

    return writer.toString();
}