Example usage for javax.xml.transform OutputKeys VERSION

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

Introduction

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

Prototype

String VERSION

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

Click Source Link

Document

version = nmtoken.

Usage

From source file:Main.java

public static String getXml(Document doc) {
    DOMSource doms = new DOMSource(doc);
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    String xml = null;/* w  ww. ja v  a  2  s  .c  o m*/
    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        Properties properties = t.getOutputProperties();
        properties.setProperty(OutputKeys.ENCODING, "GB2312");
        properties.setProperty(OutputKeys.METHOD, "xml");//!
        properties.setProperty(OutputKeys.VERSION, "1.0");
        properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperties(properties);
        t.transform(doms, sr);
        String dtd = doc.getDoctype().getInternalSubset();
        if ((null != dtd) && (dtd.length() > 0)) {
            dtd = "\n<!DOCTYPE Catalog [\n" + dtd + "]>\n";
        }
        ;
        xml = "<?xml version=\"1.0\" encoding=\"GB2312\"?>" + dtd;
        xml += sw.toString();
    } catch (TransformerConfigurationException tce) {
        //"Transformer Configuration Exception\n-----"
    } catch (TransformerException te) {
        //"Transformer Exception\n---------"
    }
    return xml;
}

From source file:Main.java

public static void setCommonOutputProperties(final Transformer transformer, final boolean indentOutput)
        throws TransformerConfigurationException {
    transformer.setOutputProperty(OutputKeys.METHOD, XML);
    transformer.setOutputProperty(OutputKeys.ENCODING, UTF_8);
    transformer.setOutputProperty(OutputKeys.VERSION, VERSION);
    if (indentOutput) {
        transformer.setOutputProperty(OutputKeys.INDENT, YES);
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
    } else {// w  w  w.jav a2s  . co  m
        transformer.setOutputProperty(OutputKeys.INDENT, NO);
    }
}

From source file:Main.java

/**
 * Writes an xml representation to a stream.
 *
 * @param doc//from w w w .ja  v a  2  s  . co  m
 *          the document
 * @param out
 *          the output stream
 * @throws IOException
 *           if there is an error transforming the dom to a stream
 */
public static void toXml(Document doc, OutputStream out) throws IOException {
    try {
        DOMSource domSource = new DOMSource(doc);
        StreamResult result = new StreamResult(out);
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.VERSION, doc.getXmlVersion());
        transformer.transform(domSource, result);
    } catch (TransformerException e) {
        throw new IOException("unable to transform dom to a stream");
    }
}

From source file:com.sdl.odata.renderer.util.PrettyPrinter.java

/**
 * Pretty-print a given XML.// w ww. j a  v a2s  .  c om
 *
 * @param xml The not-formatted XML.
 * @return The pretty-printed XML.
 */
public static String prettyPrintXml(String xml) throws TransformerException, IOException {

    Source xmlInput = new StreamSource(new StringReader(xml));
    try (StringWriter stringWriter = new StringWriter()) {
        StreamResult xmlOutput = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        transformerFactory.setAttribute("indent-number", DEFAULT_INDENT);
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, StandardCharsets.UTF_8.name());
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(xmlInput, xmlOutput);

        return xmlOutput.getWriter().toString();
    }
}

From source file:Main.java

/**
 * Saves a WC3 DOM by writing it to an XML document.
 *
 * @param doc The WC3 DOM document object.
 * @param docPath The full path to the XML document.
 * @param encoding Encoding scheme to use for the XML document, e.g.,
 * "UTF-8."// w  ww.  j a  v  a  2  s  . c om
 * @throws TransformerConfigurationException
 * @throws FileNotFoundException
 * @throws UnsupportedEncodingException
 * @throws TransformerException
 * @throws IOException
 */
public static void saveDocument(final Document doc, String encoding, String docPath)
        throws TransformerConfigurationException, FileNotFoundException, UnsupportedEncodingException,
        TransformerException, IOException {
    TransformerFactory xf = TransformerFactory.newInstance();
    xf.setAttribute("indent-number", 1); //NON-NLS
    Transformer xformer = xf.newTransformer();
    xformer.setOutputProperty(OutputKeys.METHOD, "xml"); //NON-NLS
    xformer.setOutputProperty(OutputKeys.INDENT, "yes"); //NON-NLS
    xformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    xformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); //NON-NLS
    xformer.setOutputProperty(OutputKeys.VERSION, "1.0");
    File file = new File(docPath);
    try (FileOutputStream stream = new FileOutputStream(file)) {
        Result out = new StreamResult(new OutputStreamWriter(stream, encoding));
        xformer.transform(new DOMSource(doc), out);
        stream.flush();
    }
}

From source file:net.sf.joost.emitter.XmlEmitter.java

/** Constructor */
public XmlEmitter(Writer writer, String encoding, Properties outputProperties) {
    super(writer, encoding);

    if (outputProperties != null) {
        String val;
        val = outputProperties.getProperty(OutputKeys.OMIT_XML_DECLARATION);
        if (val != null)
            propOmitXmlDeclaration = val.equals("yes");
        if (!encoding.equals("UTF-8") && !encoding.equals("UTF-16"))
            propOmitXmlDeclaration = false;

        val = outputProperties.getProperty(OutputKeys.STANDALONE);
        if (val != null)
            propStandalone = val.equals("yes");

        val = outputProperties.getProperty(OutputKeys.VERSION);
        if (val != null)
            propVersion = val;
    }/*  ww  w . j a  va2  s  . c om*/
}

From source file:org.alloy.metal.xml.merge.ImportProcessor.java

public List<ResourceInputStream> extract(List<ResourceInputStream> sources) throws MergeException {
    try {//from  w ww .j a v a 2  s.  c  om
        DynamicResourceIterator resourceList = new DynamicResourceIterator();
        resourceList.addAll(sources);

        while (resourceList.hasNext()) {
            ResourceInputStream myStream = resourceList.nextResource();
            Document doc = builder.parse(myStream);
            NodeList nodeList = (NodeList) xPath.evaluate(IMPORT_PATH, doc, XPathConstants.NODESET);
            int length = nodeList.getLength();
            for (int j = 0; j < length; j++) {
                Element element = (Element) nodeList.item(j);
                Resource resource = loader.getResource(element.getAttribute("resource"));
                ResourceInputStream ris = new ResourceInputStream(resource.getInputStream(),
                        resource.getURL().toString());
                resourceList.addEmbeddedResource(ris);
                element.getParentNode().removeChild(element);
            }
            if (length > 0) {
                TransformerFactory tFactory = TransformerFactory.newInstance();
                Transformer xmlTransformer = tFactory.newTransformer();
                xmlTransformer.setOutputProperty(OutputKeys.VERSION, "1.0");
                xmlTransformer.setOutputProperty(OutputKeys.ENCODING, _String.CHARACTER_ENCODING.toString());
                xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
                xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");

                DOMSource source = new DOMSource(doc);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));
                StreamResult result = new StreamResult(writer);
                xmlTransformer.transform(source, result);

                byte[] itemArray = baos.toByteArray();

                resourceList.set(resourceList.getPosition() - 1, new ResourceInputStream(
                        new ByteArrayInputStream(itemArray), null, myStream.getNames()));
            } else {
                myStream.reset();
            }
        }

        return resourceList;
    } catch (Exception e) {
        throw new MergeException(e);
    }
}

From source file:com.alfaariss.oa.util.configuration.handler.dummy.DummyConfigurationHandler.java

/**
 * Save the configuration to the screen.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 *//*  w  w  w . ja  v  a  2 s  .  c om*/
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(System.out));
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    }
}

From source file:de.betterform.connector.xslt.XSLTSubmissionHandler.java

/**
 * Serializes and submits the specified instance data over the
 * <code>xslt</code> protocol.
 *
 * @param submission the submission issuing the request.
 * @param instance the instance data to be serialized and submitted.
 * @return xslt transformation result.//  ww  w.  jav  a 2 s  .  c o m
 * @throws XFormsException if any error occurred during submission.
 */
public Map submit(Submission submission, Node instance) throws XFormsException {
    try {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("uri: " + getURI());
        }

        URI uri = ConnectorHelper.resolve(submission.getContainerObject().getProcessor().getBaseURI(),
                getURI());
        Map parameters = ConnectorHelper.getURLParameters(uri);
        URI stylesheetURI = ConnectorHelper.removeURLParameters(uri);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("stylesheet uri: " + stylesheetURI);
        }

        // pass output properties from submission
        CachingTransformerService transformerService = (CachingTransformerService) getContext()
                .get(TransformerService.TRANSFORMER_SERVICE);

        if (transformerService == null) {
            if (uri.getScheme().equals("http")) {
                transformerService = new CachingTransformerService(new HttpResourceResolver());
            } else if (uri.getScheme().equals("file")) {
                transformerService = new CachingTransformerService(new FileResourceResolver());
            } else {
                throw new XFormsException(
                        "Protocol " + stylesheetURI.getScheme() + " not supported for XSLT Submission Handler");
            }
        }

        if (parameters != null && parameters.get("nocache") != null) {
            transformerService.setNoCache(true);
        }

        Transformer transformer = transformerService.getTransformer(stylesheetURI);

        if (submission.getVersion() != null) {
            transformer.setOutputProperty(OutputKeys.VERSION, submission.getVersion());
        }
        if (submission.getIndent() != null) {
            transformer.setOutputProperty(OutputKeys.INDENT,
                    Boolean.TRUE.equals(submission.getIndent()) ? "yes" : "no");
        }
        if (submission.getMediatype() != null) {
            transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, submission.getMediatype());
        }
        if (submission.getEncoding() != null) {
            transformer.setOutputProperty(OutputKeys.ENCODING, submission.getEncoding());
        } else {
            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        }
        if (submission.getOmitXMLDeclaration() != null) {
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,
                    Boolean.TRUE.equals(submission.getOmitXMLDeclaration()) ? "yes" : "no");
        }
        if (submission.getStandalone() != null) {
            transformer.setOutputProperty(OutputKeys.STANDALONE,
                    Boolean.TRUE.equals(submission.getStandalone()) ? "yes" : "no");
        }
        if (submission.getCDATASectionElements() != null) {
            transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS,
                    submission.getCDATASectionElements());
        }

        // pass parameters form uri if any
        if (parameters != null) {
            Iterator iterator = parameters.keySet().iterator();
            String name;
            while (iterator.hasNext()) {
                name = (String) iterator.next();
                transformer.setParameter(name, parameters.get(name));
            }
        }

        // transform instance to byte array
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        long start = System.currentTimeMillis();

        DOMSource domSource;
        //check for 'parse' param
        String parseParam = null;
        if (parameters.containsKey("parseString")) {
            parseParam = (String) parameters.get("parseString");
        }
        if (parseParam != null && parseParam.equalsIgnoreCase("true")) {
            String xmlString = DOMUtil.getTextNodeAsString(instance);
            domSource = new DOMSource(DOMUtil.parseString(xmlString, true, false));
        } else {
            domSource = new DOMSource(instance);
        }

        transformer.transform(domSource, new StreamResult(outputStream));
        long end = System.currentTimeMillis();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("transformation time: " + (end - start) + " ms");
        }

        // create input stream from result
        InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        Map response = new HashMap();
        response.put(XFormsProcessor.SUBMISSION_RESPONSE_STREAM, inputStream);

        return response;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:com.alfaariss.oa.util.configuration.handler.text.PlainTextConfigurationHandler.java

/**
 * Writes the configuration to System.out.
 * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document)
 */// ww  w.  ja  v a  2s .c  om
public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException {
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.VERSION, "1.0");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(System.out));
    } catch (TransformerException e) {
        _logger.error("Error while transforming document", e);
        throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE);
    } catch (Exception e) {
        _logger.error("Internal error during write of configuration", e);
        throw new ConfigurationException(SystemErrors.ERROR_INTERNAL);
    }
}