Example usage for org.dom4j.io XMLWriter XMLWriter

List of usage examples for org.dom4j.io XMLWriter XMLWriter

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter XMLWriter.

Prototype

public XMLWriter(OutputStream out, OutputFormat format) throws UnsupportedEncodingException 

Source Link

Usage

From source file:com.qagen.osfe.programData.readerWriter.ReaderWriter.java

License:Apache License

protected void saveDocument() {
    try {// w ww  .j  a va 2 s . c om
        final OutputFormat format = OutputFormat.createPrettyPrint();
        final FileWriter writer = new FileWriter(fileName);
        final XMLWriter xmlWriter = new XMLWriter(writer, format);

        xmlWriter.write(document);
        xmlWriter.close();
    } catch (IOException e) {
        throw new ProgramDataException(e);
    }
}

From source file:com.rockagen.commons.util.XmlUtil.java

License:Apache License

/**
 * Format xml/*  w w w.j  a  va 2s.  c o  m*/
 *
 * @param xmlStr   xml String
 * @param formater {@link OutputFormat}
 * @return format String
 */
public static String format(String xmlStr, OutputFormat formater) {
    if (CommUtil.isBlank(xmlStr))
        return xmlStr;

    SAXReader reader = new SAXReader();
    StringReader sr = new StringReader(xmlStr);

    Document doc;
    XMLWriter writer = null;
    StringWriter sw = new StringWriter();
    try {
        doc = reader.read(sr);
        writer = new XMLWriter(sw, formater);
        writer.write(doc);
        return sw.toString();
    } catch (DocumentException e) {
        log.error("{}", e.getMessage(), e);
    } catch (IOException e) {
        log.error("{}", e.getMessage(), e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ignored) {
            }
        }

    }

    return xmlStr;
}

From source file:com.rowtheboat.gui.OptionsSingleton.java

License:Open Source License

/**
 * This method saves the options to the options.xml file
 *///from w  w  w.ja va  2 s  . co m
public void saveOptions() throws SAXException, IOException {

    /* Start the document */
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(optionsFile), format);
    writer.startDocument();

    /* Add the main options section */
    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("Options");

    /* Standard options */
    DefaultElement standardElement = new DefaultElement("Standard");
    standardElement.addElement("FullStrokeData").addText(getFullStrokeData() + "");
    standardElement.addElement("BoatSmoothing").addText(getBoatSmoothing() + "");
    root.add(standardElement);

    /* Input options */
    DefaultElement inputElement = new DefaultElement("Input");
    inputElement.addElement("SerialPort").addText(getSerialPort());
    root.add(inputElement);

    /* Race options */
    DefaultElement raceElement = new DefaultElement("Race");
    raceElement.addElement("Countdown").addText(getDelay() + "");
    root.add(raceElement);

    /* End the document */
    writer.write(root);
    writer.endDocument();
    writer.close();
}

From source file:com.safi.workshop.sqlexplorer.history.SQLHistory.java

License:Open Source License

/**
 * Save all the used queries into a file, so that we can reuse them next time.
 *///  w w  w  .  j  a  v a 2 s .  co  m
public void save() {

    try {
        File file = new File(ApplicationFiles.SQLHISTORY_FILE_NAME_V350);
        Element root = new DefaultElement(HISTORY);
        for (SQLHistoryElement elem : _history)
            root.add(elem.describeAsXml());
        XMLWriter xmlWriter = new XMLWriter(new FileWriter(file), OutputFormat.createPrettyPrint());
        xmlWriter.write(root);
        xmlWriter.flush();
        xmlWriter.close();

        // Get rid of old versions
        new File(ApplicationFiles.SQLHISTORY_FILE_NAME_V300).delete();

    } catch (IOException e) {
        SQLExplorerPlugin.error("Couldn't save sql history.", e);
    }

}

From source file:com.sammyun.util.SettingUtils.java

License:Open Source License

/**
 * /*from  w w w.ja v a 2 s  . co  m*/
 * 
 * @param setting 
 */
public static void set(Setting setting) {
    try {
        File preschoolEduXmlFile = new ClassPathResource(CommonAttributes.PRESCHOOLEDU_XML_PATH).getFile();
        Document document = new SAXReader().read(preschoolEduXmlFile);
        List<Element> elements = document.selectNodes("/preschoolEdu/setting");
        for (Element element : elements) {
            try {
                String name = element.attributeValue("name");
                String value = beanUtils.getProperty(setting, name);
                Attribute attribute = element.attribute("value");
                attribute.setValue(value);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            } catch (InvocationTargetException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
                logger.error(e.getMessage());
            }
        }

        FileOutputStream fileOutputStream = null;
        XMLWriter xmlWriter = null;
        try {
            OutputFormat outputFormat = OutputFormat.createPrettyPrint();
            outputFormat.setEncoding("UTF-8");
            outputFormat.setIndent(true);
            outputFormat.setIndent("   ");
            outputFormat.setNewlines(true);
            fileOutputStream = new FileOutputStream(preschoolEduXmlFile);
            xmlWriter = new XMLWriter(fileOutputStream, outputFormat);
            xmlWriter.write(document);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                }
            }
            IOUtils.closeQuietly(fileOutputStream);
        }

        Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME);
        cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting));
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e.getMessage());
    }
}

From source file:com.sap.data.db.dao.StructureUtil.java

private void save(Document document, String filepath) throws IOException {
    document.addDocType(this.HIBERNATE_MAPPING, this.HIBERNATE_MAPPING_EN, this.HIBERNATE_MAPPING_DTD);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");

    XMLWriter writer = new XMLWriter(new FileWriter(new File(filepath)), format);
    writer.write(document);/* w w  w.  j a v a  2 s.  c om*/
    writer.close();
}

From source file:com.servoy.extension.install.LibActivationHandler.java

License:Open Source License

protected void writeBackXML(Document doc, File f, String encoding)
        throws IOException, TransformerFactoryConfigurationError, TransformerException, DocumentException {
    BufferedOutputStream os = null;
    try {/* ww  w  .  java  2s.c o  m*/
        os = new BufferedOutputStream(new FileOutputStream(f));
        doc.normalize();
        StringWriter sw = new StringWriter(1024);
        DOMSource source = new DOMSource(doc);
        Transformer newTransformer = TransformerFactory.newInstance().newTransformer();
        newTransformer.setOutputProperty(OutputKeys.ENCODING, encoding);
        newTransformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        newTransformer.transform(source, new StreamResult(sw));

        // normally the transformer code above should have been enough for producing pretty formatted XML (needed so that repeated remove/restore of tags
        // doesn't produce endless newlines or other bad looking XML); but it seems that with some versions of the JDK that doesn't do it's job so we use dom4j
        final OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encoding);
        final XMLWriter writer = new XMLWriter(os, format);
        writer.write(DocumentHelper.parseText(sw.toString()));
    } finally {
        Utils.closeOutputStream(os);
    }

}

From source file:com.smartwork.im.StreamError.java

License:Open Source License

public String toString() {
    StringWriter out = new StringWriter();
    XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
    try {//from   w  ww  .ja v a 2s  .  co  m
        writer.write(element);
    } catch (Exception e) {
    }
    return out.toString();
}

From source file:com.sofrecom.MybatisGenXmlHandler.java

public void saveDocument(Document document)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    try (FileOutputStream fos = new FileOutputStream(Configuration.XMLTemplate)) {
        OutputFormat format = OutputFormat.createPrettyPrint();
        // Create the xml writer by passing outputstream and format
        XMLWriter writer = new XMLWriter(fos, format);
        // Write to the xml document
        writer.write(document);/*w w w  . j ava 2 s .c  om*/
        // Flush after done
        writer.flush();
        writer.close();
    }
}

From source file:com.stratumsoft.xmlgen.SchemaTypeXmlGenerator.java

License:Open Source License

/**
 * Generate an xml representation of the dom structure of the schema element
 *
 * @param elName        the QName of the element for which the XML should be generated
 * @param isPrettyPrint if true formats and indents the generated xml
 * @return the xml instance for the schema element, or empty string if no element with the given qname was found
 *///from  w  ww  .  j  ava  2  s  .co  m
public String generateXml(QName elName, boolean isPrettyPrint) {
    String xml = "";
    if (elName != null && schemaColl != null) {

        Document doc = factory.createDocument("utf-8"); //NON-NLS
        Element el = generateElement(elName);
        if (el != null) {
            doc.add(el);
        } else {
            logger.warn("got null for element generated for qname: {}", elName);
        }

        if (isPrettyPrint)
            outputFormat = OutputFormat.createPrettyPrint();

        StringWriter sw = new StringWriter();
        writer = new XMLWriter(sw, outputFormat);
        try {
            writer.write(doc);
            xml = sw.toString();
            logger.trace("Serialized dom4j doc to xml string: {}", xml);

        } catch (IOException e) {
            logger.error("dom4j Document to xml creation error", e);
        }

    }

    return xml;
}