Java Code Examples for org.dom4j.io.OutputFormat#createPrettyPrint()

The following examples show how to use org.dom4j.io.OutputFormat#createPrettyPrint() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WriteToXMLUtil.java    From CEC-Automatic-Annotation with Apache License 2.0 6 votes vote down vote up
public static boolean writeToXML(Document document, String tempPath) {
	try {
		// 使用XMLWriter写入,可以控制格式,经过调试,发现这种方式会出现乱码,主要是因为Eclipse中xml文件和JFrame中文件编码不一致造成的
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding(EncodingUtil.CHARSET_UTF8);
		// format.setSuppressDeclaration(true);//这句话会压制xml文件的声明,如果为true,就不打印出声明语句
		format.setIndent(true);// 设置缩进
		format.setIndent("	");// 空行方式缩进
		format.setNewlines(true);// 设置换行
		XMLWriter writer = new XMLWriter(new FileWriterWithEncoding(new File(tempPath), EncodingUtil.CHARSET_UTF8), format);
		writer.write(document);
		writer.close();
	} catch (IOException e) {
		e.printStackTrace();
		MyLogger.logger.error("写入xml文件出错!");
		return false;
	}
	return true;
}
 
Example 2
Source File: QTIExportImportTest.java    From olat with Apache License 2.0 6 votes vote down vote up
private static QTIDocument exportAndImportToQTIFormat(QTIDocument qtiDocOrig) throws IOException {
    Document qtiXmlDoc = qtiDocOrig.getDocument();
    OutputFormat outformat = OutputFormat.createPrettyPrint();

    String fileName = qtiDocOrig.getAssessment().getTitle() + "QTIFormat.xml";
    OutputStreamWriter qtiXmlOutput = new OutputStreamWriter(new FileOutputStream(new File(TEMP_DIR, fileName)), Charset.forName("UTF-8"));
    XMLWriter writer = new XMLWriter(qtiXmlOutput, outformat);
    writer.write(qtiXmlDoc);
    writer.flush();
    writer.close();

    XMLParser xmlParser = new XMLParser(new IMSEntityResolver());
    Document doc = xmlParser.parse(new FileInputStream(new File(TEMP_DIR, fileName)), true);
    ParserManager parser = new ParserManager();
    QTIDocument qtiDocRestored = (QTIDocument) parser.parse(doc);
    return qtiDocRestored;
}
 
Example 3
Source File: EnhanceBaseBuilder.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static File createPernsistenceXml(List<Class<?>> classes, File directory) throws Exception {
	Document document = DocumentHelper.createDocument();
	Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
	persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
			"http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
	persistence.addAttribute("version", "2.0");
	Element unit = persistence.addElement("persistence-unit");
	unit.addAttribute("name", "enhance");
	for (Class<?> o : classes) {
		Element element = unit.addElement("class");
		element.addText(o.getCanonicalName());
	}
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	File file = new File(directory, "persistence.xml");
	XMLWriter writer = new XMLWriter(new FileWriter(file), format);
	writer.write(document);
	writer.close();
	return file;
}
 
Example 4
Source File: ImportFileUpdater.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Get the writer for the import file
 * 
 * @param destination	the destination XML import file
 * @return				the XML writer
 */
private XMLWriter getWriter(String destination)
{
	try
	{
		 // Define output format
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setNewLineAfterDeclaration(false);
        format.setIndentSize(INDENT_SIZE);
        format.setEncoding(this.fileEncoding);

        return new XMLWriter(new FileOutputStream(destination), format);
	}
       catch (Exception exception)
       {
       	throw new AlfrescoRuntimeException("Unable to create XML writer.", exception);
       }
}
 
Example 5
Source File: XMLTransferReportWriter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Start the transfer report
 */
public void startTransferReport(String encoding, Writer writer) throws SAXException
{
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding(encoding);
    
    this.writer = new XMLWriter(writer, format);
    this.writer.startDocument();
    
    this.writer.startPrefixMapping(PREFIX, TransferReportModel2.TRANSFER_REPORT_MODEL_2_0_URI);

    // Start Transfer Manifest  // uri, name, prefix
    this.writer.startElement(TransferReportModel2.TRANSFER_REPORT_MODEL_2_0_URI, TransferReportModel.LOCALNAME_TRANSFER_REPORT,  PREFIX + ":" + TransferReportModel.LOCALNAME_TRANSFER_REPORT, EMPTY_ATTRIBUTES);
}
 
Example 6
Source File: DOM4JSerializer.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void exportToFile(ExportInteraction exportInteraction, ExtensionFileFilter fileFilter, DOM4JSettingsNode settingsNode) {
    File file = promptForFile(exportInteraction, fileFilter);
    if (file == null) {
        //the user canceled.
        return;
    }

    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        LOGGER.error("Could not write to file: " + file.getAbsolutePath(), e);
        exportInteraction.reportError("Could not write to file: " + file.getAbsolutePath());
        return;
    }

    try {
        XMLWriter xmlWriter = new XMLWriter(fileOutputStream, OutputFormat.createPrettyPrint());
        Element rootElement = settingsNode.getElement();
        rootElement.detach();

        Document document = DocumentHelper.createDocument(rootElement);

        xmlWriter.write(document);
    } catch (Throwable t) {
        LOGGER.error("Internal error. Failed to save.", t);
        exportInteraction.reportError("Internal error. Failed to save.");
    } finally {
        closeQuietly(fileOutputStream);
    }
}
 
Example 7
Source File: AddMessages.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@SuppressFBWarnings("DM_EXIT")
public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("Usage: " + AddMessages.class.getName() + " <input collection> <output collection>");
        System.exit(1);
    }

    // Load plugins, in order to get message files
    DetectorFactoryCollection.instance();

    String inputFile = args[0];
    String outputFile = args[1];
    Project project = new Project();

    SortedBugCollection inputCollection = new SortedBugCollection(project);
    inputCollection.readXML(inputFile);

    Document document = inputCollection.toDocument();

    AddMessages addMessages = new AddMessages(inputCollection, document);
    addMessages.execute();

    XMLWriter writer = new XMLWriter(new BufferedOutputStream(new FileOutputStream(outputFile)),
            OutputFormat.createPrettyPrint());
    writer.write(document);
    writer.close();
}
 
Example 8
Source File: XmlUtil.java    From SpringBootUnity with MIT License 5 votes vote down vote up
/**
 * xml转换为字符串
 *
 * @param doc
 * @param encoding
 * @return
 * @throws Exception
 */
public static String toString(Document doc, String encoding) throws Exception {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);
    ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS, encoding), format);
    writer.write(doc);
    writer.flush();
    writer.close();
    return byteOS.toString(encoding);
}
 
Example 9
Source File: XmlUtil.java    From SpringBootUnity with MIT License 5 votes vote down vote up
/**
 * 保存文档
 *
 * @throws Exception
 */
public static void save(Document doc, String xmlPath, String encoding) throws Exception {
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(encoding);
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath), encoding), format);
    writer.write(doc);
    writer.flush();
    writer.close();
}
 
Example 10
Source File: LianlianBranchTest.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
private void writeXml(List<JSONArray> list) throws Exception {
	File file = new File(SAVE_PATH);
	if (file.exists())
		file.delete();

	// 生成一个文档
	Document document = DocumentHelper.createDocument();
	Element root = document.addElement("root");
	for (JSONArray jsonArray : list) {
		for (Object object : jsonArray) {
			JSONObject json = (JSONObject) object;
			System.out.println(json);
			Element element = root.addElement("branch");
			// 为cdr设置属性名和属性值
			element.addAttribute("branchId", json.getString("prcptcd").trim());// 支行行号
			element.addAttribute("bankCode", json.getString("bankCode").trim());// 银行类型
			element.addAttribute("cityCode", json.getString("cityCode").trim());// 城市代码
			element.addAttribute("branchName", json.getString("brabank_name").trim());// 支行名称
		}
	}
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setEncoding("UTF-8");
	XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(new File(SAVE_PATH)), "UTF-8"), format);
	// 写入新文件
	writer.write(document);
	writer.flush();
	writer.close();
}
 
Example 11
Source File: ExportSourceImporter.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private XMLWriter createXMLExporter(Writer writer)
{
    // Define output format
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setNewLineAfterDeclaration(false);
    format.setIndentSize(3);
    format.setEncoding("UTF-8");

    // Construct an XML Exporter

    XMLWriter xmlWriter = new XMLWriter(writer, format);
    return xmlWriter;
}
 
Example 12
Source File: ScenarioEditor.java    From rcrs-server with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
   Save the scenario.
   @throws ScenarioException If there is a problem saving the scenario.
*/
public void save() throws ScenarioException {
    if (saveFile == null) {
        saveAs();
    }
    if (saveFile != null) {
        LOG.debug("Saving to " + saveFile.getAbsolutePath());
        Document doc = DocumentHelper.createDocument();
        scenario.write(doc);
        try {
            if (!saveFile.exists()) {
                File parent = saveFile.getParentFile();
                if (!parent.exists()) {
                    if (!saveFile.getParentFile().mkdirs()) {
                        throw new ScenarioException("Couldn't create file " + saveFile.getPath());
                    }
                }
                if (!saveFile.createNewFile()) {
                    throw new ScenarioException("Couldn't create file " + saveFile.getPath());
                }
            }
            XMLWriter writer = new XMLWriter(new FileOutputStream(saveFile), OutputFormat.createPrettyPrint());
            writer.write(doc);
            writer.flush();
            writer.close();
        }
        catch (IOException e) {
            throw new ScenarioException(e);
        }
        baseDir = saveFile.getParentFile();
        changed = false;
    }
}
 
Example 13
Source File: MultiRepresentationTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void prettyPrint(Element element) {
	//System.out.println( element.asXML() );
	try {
		OutputFormat format = OutputFormat.createPrettyPrint();
		new XMLWriter( System.out, format ).write( element );
		System.out.println();
	}
	catch ( Throwable t ) {
		System.err.println( "Unable to pretty print element : " + t );
	}
}
 
Example 14
Source File: PermissionModel.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private InputStream processModelDocType(InputStream is, String dtdSchemaUrl) throws DocumentException, IOException
{
    SAXReader reader = new SAXReader();
    // read document without validation
    Document doc = reader.read(is);
    DocumentType docType = doc.getDocType();
    if (docType != null)
    {
        // replace DOCTYPE setting the full path to the xsd
        docType.setSystemID(dtdSchemaUrl);
    }
    else
    {
        // add the DOCTYPE
        docType = new DefaultDocumentType(doc.getRootElement().getName(), dtdSchemaUrl);
        doc.setDocType(docType);
    }

    ByteArrayOutputStream fos = new ByteArrayOutputStream();
    try
    {
        OutputFormat format = OutputFormat.createPrettyPrint(); // uses UTF-8
        XMLWriter writer = new XMLWriter(fos, format);
        writer.write(doc);
        writer.flush();
    }
    finally
    {
        fos.close();
    }
    
    return new ByteArrayInputStream(fos.toByteArray());
}
 
Example 15
Source File: XMLHelper.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void dump(Element element) {
	try {
		// try to "pretty print" it
		OutputFormat outformat = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter( System.out, outformat );
		writer.write( element );
		writer.flush();
		System.out.println( "" );
	}
	catch( Throwable t ) {
		// otherwise, just dump it
		System.out.println( element.asXML() );
	}

}
 
Example 16
Source File: PersistenceXmlHelper.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public static List<String> directWrite(String path, List<String> classNames) throws Exception {
	try {
		Document document = DocumentHelper.createDocument();
		Element persistence = document.addElement("persistence", "http://java.sun.com/xml/ns/persistence");
		persistence.addAttribute(QName.get("schemaLocation", "xsi", "http://www.w3.org/2001/XMLSchema-instance"),
				"http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd");
		persistence.addAttribute("version", "2.0");
		for (String className : classNames) {
			Element unit = persistence.addElement("persistence-unit");
			unit.addAttribute("name", className);
			unit.addAttribute("transaction-type", "RESOURCE_LOCAL");
			Element provider = unit.addElement("provider");
			provider.addText(PersistenceProviderImpl.class.getName());
			Element mapped_element = unit.addElement("class");
			mapped_element.addText(className);
			Element sliceJpaObject_element = unit.addElement("class");
			sliceJpaObject_element.addText("com.x.base.core.entity.SliceJpaObject");
			Element jpaObject_element = unit.addElement("class");
			jpaObject_element.addText("com.x.base.core.entity.JpaObject");
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");
		File file = new File(path);
		FileUtils.touch(file);
		XMLWriter writer = new XMLWriter(new FileWriter(file), format);
		writer.write(document);
		writer.close();
		return classNames;
	} catch (Exception e) {
		throw new Exception("registContainerEntity error.className:" + ListTools.toStringJoin(classNames), e);
	}
}
 
Example 17
Source File: Dom4jManyToOneTest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void print(Element elt) throws Exception {
	OutputFormat outformat = OutputFormat.createPrettyPrint();
	// outformat.setEncoding(aEncodingScheme);
	XMLWriter writer = new XMLWriter( System.out, outformat );
	writer.write( elt );
	writer.flush();
	// System.out.println( elt.asXML() );
}
 
Example 18
Source File: Dom4jUtil2.java    From egdownloader with GNU General Public License v2.0 4 votes vote down vote up
public static void writeDOM2XML(File file, Document doc) throws Exception{
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"), format);
    writer.write(doc);
    writer.close();
}
 
Example 19
Source File: WebDAVMethod.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Returns the format required for an XML response. This may vary per method.
 */
protected OutputFormat getXMLOutputFormat()
{
    // Check if debug output or XML pretty printing is enabled
    return (XMLPrettyPrint || logger.isDebugEnabled()) ? OutputFormat.createPrettyPrint() : OutputFormat.createCompactFormat();
}
 
Example 20
Source File: DataDstXml.java    From xresloader with MIT License 4 votes vote down vote up
@Override
public final byte[] build(DataDstImpl compiler) throws ConvException {
    // pretty print
    OutputFormat of = null;
    if (ProgramOptions.getInstance().prettyIndent <= 0) {
        of = OutputFormat.createCompactFormat();
    } else {
        of = OutputFormat.createPrettyPrint();
        of.setIndentSize(ProgramOptions.getInstance().prettyIndent);
    }

    // build data
    DataDstObject data_obj = build_data(compiler);

    // build xml tree
    Document doc = DocumentHelper.createDocument();
    String encoding = SchemeConf.getInstance().getKey().getEncoding();
    if (null != encoding && false == encoding.isEmpty()) {
        doc.setXMLEncoding(encoding);
        of.setEncoding(encoding);
    }

    doc.setRootElement(DocumentHelper.createElement(ProgramOptions.getInstance().xmlRootName));
    doc.getRootElement().addComment("this file is generated by xresloader, please don't edit it.");

    Element header = DocumentHelper.createElement("header");
    Element body = DocumentHelper.createElement("body");
    Element data_message_type = DocumentHelper.createElement("data_message_type");

    writeData(header, data_obj.header, header.getName());

    // body
    for (Map.Entry<String, List<Object>> item : data_obj.body.entrySet()) {
        for (Object obj : item.getValue()) {
            Element xml_item = DocumentHelper.createElement(item.getKey());

            writeData(xml_item, obj, item.getKey());

            body.add(xml_item);
        }
    }

    writeData(body, data_obj.body, body.getName());

    writeData(data_message_type, data_obj.data_message_type, data_message_type.getName());

    doc.getRootElement().add(header);
    doc.getRootElement().add(body);
    doc.getRootElement().add(data_message_type);

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(bos, of);
        writer.write(doc);

        return bos.toByteArray();
    } catch (Exception e) {
        this.logErrorMessage("write xml failed, %s", e.getMessage());
        return null;
    }
}