Example usage for javax.xml.transform OutputKeys METHOD

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

Introduction

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

Prototype

String METHOD

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

Click Source Link

Document

method = "xml" | "html" | "text" | expanded name.

Usage

From source file:channellistmaker.channelfilemaker.ChannelDocumentMaker.java

/**
 * @return ????X???ML????????//  ww  w . j ava2s  .com
 */
public String getChannelList() {
    try {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        final DocumentBuilder db = dbf.newDocumentBuilder();
        final Document document = db.newDocument();
        // >>>>> DOM??
        Element channels_e = document.createElement("channels");//<-root
        document.appendChild(channels_e);

        final Set<MultiKey<Integer>> keys = this.channels.keySet();
        for (MultiKey<Integer> key : keys) {
            Channel ch = channels.get(key);
            this.addChannelElement(document, channels_e, ch);
        }

        TransformerFactory tf = TransformerFactory.newInstance();

        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        StringWriter writer = new StringWriter();// <-??????????
        StreamResult result = new StreamResult(writer);

        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);

        return writer.toString();
    } catch (ParserConfigurationException | TransformerConfigurationException ex) {
        LOG.fatal(ex);
        return "";
    } catch (TransformerException ex) {
        LOG.fatal(ex);
        return "";
    }
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

@Autowired
public DocumentResource(FedoraRepository fedoraRepository, URNConfiguration urnConfiguration,
        FileHandlingService fileHandlingService)
        throws ParserConfigurationException, TransformerConfigurationException {
    this.fedoraRepository = fedoraRepository;
    this.urnConfiguration = urnConfiguration;
    this.fileHandlingService = fileHandlingService;

    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    documentBuilder = documentBuilderFactory.newDocumentBuilder();

    transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    xmlOutputFactory = XMLOutputFactory.newFactory();
}

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

static String xmlToString(Element doc) {
    StringWriter sw = new StringWriter();
    try {//from  www  . ja  v  a2s.c o  m
        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: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 ww . jav a2 s . c om
 * @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:tut.pori.javadocer.Javadocer.java

/**
 * /*from  w  ww. j  a  v a  2s  .c  o 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.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  w  w .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();
}

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

/**
 * execute DML//from   w  w  w .j  av a 2  s  .c  o m
 * 
 * @param userDB
 * @param strQuery
 * @param listParam
 * @param resultType
 * @throws Exception
 */
public static String executeDML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam,
        final String resultType) throws Exception {
    SqlMapClient client = TadpoleSQLManager.getInstance(userDB);
    Object effectObject = runSQLOther(userDB, strQuery, listParam);

    String strReturn = "";
    if (resultType.equals(RESULT_TYPE.CSV.name())) {
        final StringWriter stWriter = new StringWriter();
        CSVWriter csvWriter = new CSVWriter(stWriter, ',');

        String[] arryString = new String[2];
        arryString[0] = "effectrow";
        arryString[1] = String.valueOf(effectObject);
        csvWriter.writeNext(arryString);

        strReturn = stWriter.toString();
    } else if (resultType.equals(RESULT_TYPE.JSON.name())) {
        final JsonArray jsonArry = new JsonArray();
        JsonObject jsonObj = new JsonObject();
        jsonObj.addProperty("effectrow", String.valueOf(effectObject));
        jsonArry.add(jsonObj);

        strReturn = JSONUtil.getPretty(jsonArry.toString());
    } else {//if(resultType.equals(RESULT_TYPE.XML.name())) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        final Document doc = builder.newDocument();
        final Element results = doc.createElement("Results");
        doc.appendChild(results);

        Element row = doc.createElement("Row");
        results.appendChild(row);
        Element node = doc.createElement("effectrow");
        node.appendChild(doc.createTextNode(String.valueOf(effectObject)));
        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");

        final StringWriter stWriter = new StringWriter();
        StreamResult sr = new StreamResult(stWriter);
        transformer.transform(domSource, sr);

        strReturn = stWriter.toString();
    }

    return strReturn;
}

From source file:dicoogle.ua.dim.DIMGeneric.java

public String getXML() {

    StringWriter writer = new StringWriter();

    StreamResult streamResult = new StreamResult(writer);
    SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
    //      SAX2.0 ContentHandler.
    TransformerHandler hd = null;
    try {/*from   w  w w  .j av a 2 s .  c o  m*/
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException ex) {
        Logger.getLogger(DIMGeneric.class.getName()).log(Level.SEVERE, null, ex);
    }
    Transformer serializer = hd.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.METHOD, "xml");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    hd.setResult(streamResult);
    try {
        hd.startDocument();

        AttributesImpl atts = new AttributesImpl();
        hd.startElement("", "", "DIM", atts);

        for (Patient p : this.patients) {
            atts.clear();
            atts.addAttribute("", "", "name", "", p.getPatientName().trim());
            atts.addAttribute("", "", "id", "", p.getPatientID().trim());
            hd.startElement("", "", "Patient", atts);

            for (Study s : p.getStudies()) {
                atts.clear();
                atts.addAttribute("", "", "date", "", s.getStudyData().trim());
                atts.addAttribute("", "", "id", "", s.getStudyInstanceUID().trim());

                hd.startElement("", "", "Study", atts);

                for (Serie serie : s.getSeries()) {
                    atts.clear();
                    atts.addAttribute("", "", "modality", "", serie.getModality().trim());
                    atts.addAttribute("", "", "id", "", serie.getSerieInstanceUID().trim());

                    hd.startElement("", "", "Serie", atts);

                    ArrayList<URI> img = serie.getImageList();
                    ArrayList<String> uid = serie.getSOPInstanceUIDList();
                    int size = img.size();
                    for (int i = 0; i < size; i++) {
                        atts.clear();
                        atts.addAttribute("", "", "path", "", img.get(i).toString().trim());
                        atts.addAttribute("", "", "uid", "", uid.get(i).trim());

                        hd.startElement("", "", "Image", atts);
                        hd.endElement("", "", "Image");
                    }
                    hd.endElement("", "", "Serie");
                }
                hd.endElement("", "", "Study");
            }
            hd.endElement("", "", "Patient");
        }
        hd.endElement("", "", "DIM");

    } catch (SAXException ex) {
        Logger.getLogger(DIMGeneric.class.getName()).log(Level.SEVERE, null, ex);
    }

    return writer.toString();
}

From source file:fr.adfab.magebeans.processes.CreateModuleProcess.java

protected void _writeConfigXmlFile() {
    try {//from  w ww  .  j  a  v  a2  s.  com
        String configFile = this.moduleDir + "/" + this.CONFIG_PATH;
        Transformer tr = TransformerFactory.newInstance().newTransformer();
        tr.setOutputProperty(OutputKeys.INDENT, "yes");
        tr.setOutputProperty(OutputKeys.METHOD, "xml");
        tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        tr.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(configFile)));
    } catch (TransformerConfigurationException ex) {
        System.out.println(ex.getMessage());
    } catch (TransformerException | FileNotFoundException ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:de.gbv.ole.Marc21ToOleBulk.java

/**
 * Set the <code>Result</code> associated with this
 * <code>TransformerHandler</code> to be used for the transformation.
 *
 * @param result    the Result to be used for the transformation
 *///from w  ww. j a v  a 2  s . c o m
protected final void setHandler(final Result result) {
    try {
        TransformerFactory factory = TransformerFactory.newInstance();
        if (!factory.getFeature(SAXTransformerFactory.FEATURE)) {
            throw new UnsupportedOperationException("SAXTransformerFactory is not supported");
        }

        SAXTransformerFactory saxFactory = (SAXTransformerFactory) factory;
        handler = saxFactory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
        handler.setResult(result);

    } catch (Exception e) {
        throw new MarcException(e.getMessage(), e);
    }
}