Java Code Examples for org.dom4j.io.XMLWriter#write()

The following examples show how to use org.dom4j.io.XMLWriter#write() . 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: AbstractXMLRequestCreatorBase.java    From powermock-examples-maven with Apache License 2.0 7 votes vote down vote up
/**
 * Convert a dom4j xml document to a byte[].
 * 
 * @param document
 *            The document to convert.
 * @return A <code>byte[]</code> representation of the xml document.
 * @throws IOException
 *             If an exception occurs when converting the document.
 */
public byte[] convertDocumentToByteArray(Document document)
		throws IOException {
	ByteArrayOutputStream stream = new ByteArrayOutputStream();
	XMLWriter writer = new XMLWriter(stream);
	byte[] documentAsByteArray = null;
	try {
		writer.write(document);
	} finally {
		writer.close();
		stream.flush();
		stream.close();
	}
	documentAsByteArray = stream.toByteArray();
	return documentAsByteArray;
}
 
Example 2
Source File: XSLConfiguration.java    From CogniCrypt with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public File persistConf() throws IOException {
	final XMLClaferParser parser = new XMLClaferParser();
	Document configInXMLFormat = parser.displayInstanceValues(instance, this.options);
	if (configInXMLFormat != null) {
		final OutputFormat format = OutputFormat.createPrettyPrint();
		final XMLWriter writer = new XMLWriter(new FileWriter(pathOnDisk), format);
		writer.write(configInXMLFormat);
		writer.close();
		configInXMLFormat = null;

		return new File(pathOnDisk);
	} else {
		Activator.getDefault().logError(Constants.NO_XML_INSTANCE_FILE_TO_WRITE);
	}
	return null;

}
 
Example 3
Source File: TestTool.java    From ofdrw with Apache License 2.0 6 votes vote down vote up
/**
 * 生成XML 并打印打控制台
 *
 * @param name 文件名称
 * @param call 元素添加方法
 */
public static void genXml(String name, Consumer<Document> call) {
    Document doc = DocumentHelper.createDocument();
    String filePath = TEST_DEST + File.separator + name + ".xml";
    try (FileOutputStream out = new FileOutputStream(filePath)) {
        call.accept(doc);

        // 格式化打印到控制台
        XMLWriter writerToSout = new XMLWriter(System.out, FORMAT);
        writerToSout.write(doc);

        // 打印打到文件
        XMLWriter writeToFile = new XMLWriter(out, FORMAT);
        writeToFile.write(doc);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: Command.java    From ApkCustomizationTool with Apache License 2.0 6 votes vote down vote up
/**
 * 修改bools.xml文件内容
 *
 * @param file  bools文件
 * @param bools 修改的值列表
 */
private void updateBools(File file, List<Bools> bools) {
    try {
        if (bools == null || bools.isEmpty()) {
            return;
        }
        Document document = new SAXReader().read(file);
        List<Element> elements = document.getRootElement().elements();
        elements.forEach(element -> {
            final String name = element.attribute("name").getValue();
            bools.forEach(s -> {
                if (s.getName().equals(name)) {
                    element.setText(s.getValue());
                    callback("修改 bools.xml name='" + name + "' value='" + s.getValue() + "'");
                }
            });
        });
        XMLWriter writer = new XMLWriter(new FileOutputStream(file));
        writer.write(document);
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: DomUtils.java    From kafka-eagle with Apache License 2.0 6 votes vote down vote up
public static void getTomcatServerXML(String xml, String modifyPort) throws Exception {
	SAXReader reader = new SAXReader();
	Document document = reader.read(new File(xml));
	Element node = document.getRootElement();
	List<?> tasks = node.elements();
	for (Object task : tasks) {
		Element taskNode = (Element) task;
		String name = taskNode.attributeValue("name");
		if ("Catalina".equals(name)) {
			String protocol = taskNode.element("Connector").attributeValue("protocol");
			if ("HTTP/1.1".equals(protocol)) {
				taskNode.element("Connector").addAttribute("port", modifyPort);
			}
		}
	}

	XMLWriter writer = new XMLWriter(new FileWriter(xml));
	writer.write(document);
	writer.close();
}
 
Example 6
Source File: FilePersister.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * Persist results for this user/aiid as an XML document. dlPointer is aiid in this case.
 * 
 * @param doc
 * @param type
 * @param info
 */
public static void createResultsReporting(final Document doc, final Identity subj, final String type, final long aiid) {
    final File fUserdataRoot = new File(getQtiFilePath());
    final String path = RES_REPORTING + File.separator + subj.getName() + File.separator + type;
    final File fReportingDir = new File(fUserdataRoot, path);
    try {
        fReportingDir.mkdirs();
        final OutputStream os = new FileOutputStream(new File(fReportingDir, aiid + ".xml"));
        final Element element = doc.getRootElement();
        final XMLWriter xw = new XMLWriter(os, new OutputFormat("  ", true));
        xw.write(element);
        // closing steams
        xw.close();
        os.close();
    } catch (final Exception e) {
        throw new OLATRuntimeException(FilePersister.class,
                "Error persisting results reporting for subject: '" + subj.getName() + "'; assessment id: '" + aiid + "'", e);
    }
}
 
Example 7
Source File: Command.java    From ApkCustomizationTool with Apache License 2.0 6 votes vote down vote up
/**
 * 修改strings.xml文件内容
 *
 * @param file    strings文件
 * @param strings 修改的值列表
 */
private void updateStrings(File file, List<Strings> strings) {
    try {
        if (strings == null || strings.isEmpty()) {
            return;
        }
        Document document = new SAXReader().read(file);
        List<Element> elements = document.getRootElement().elements();
        elements.forEach(element -> {
            final String name = element.attribute("name").getValue();
            strings.forEach(s -> {
                if (s.getName().equals(name)) {
                    element.setText(s.getValue());
                    callback("修改 strings.xml name='" + name + "' value='" + s.getValue() + "'");
                }
            });
        });
        XMLWriter writer = new XMLWriter(new FileOutputStream(file));
        writer.write(document);
        writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 8
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 9
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 10
Source File: XmlClobType.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void nullSafeSet(PreparedStatement ps, Object value, int index, SessionImplementor session) throws SQLException, HibernateException {
    if (value == null) {
        ps.setNull(index, sqlTypes()[0]);
    } else {
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            XMLWriter writer = new XMLWriter(bytes,OutputFormat.createCompactFormat());
            writer.write((Document)value);
            writer.flush(); writer.close();
            ps.setCharacterStream(index, new CharArrayReader(bytes.toString().toCharArray(),0,bytes.size()), bytes.size());
        } catch (IOException e) {
            throw new HibernateException(e.getMessage(),e);
        }
    }
}
 
Example 11
Source File: XMLUtil.java    From APICloud-Studio with GNU General Public License v3.0 5 votes vote down vote up
public static String formatXml(String str) throws Exception {
 Document document = null;
 document = DocumentHelper.parseText(str.trim());
 // 格式化输出格式
 OutputFormat format = OutputFormat.createPrettyPrint();
 format.setEncoding("UTF-8");
 StringWriter writer = new StringWriter();
 // 格式化输出流
 XMLWriter xmlWriter = new XMLWriter(writer, format);
 // 将document写入到输出流
 xmlWriter.write(document);
 xmlWriter.close();

 return writer.toString();
}
 
Example 12
Source File: XmlUtils.java    From iaf with Apache License 2.0 5 votes vote down vote up
public static String canonicalize(String input) throws DocumentException, IOException {
	if (StringUtils.isEmpty(input)) {
		return null;
	}
	org.dom4j.Document doc = DocumentHelper.parseText(input);
	StringWriter sw = new StringWriter();
	OutputFormat format = OutputFormat.createPrettyPrint();
	format.setExpandEmptyElements(true);
	XMLWriter xw = new XMLWriter(sw, format);
	xw.write(doc);
	return sw.toString();
}
 
Example 13
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 14
Source File: XMLUtil.java    From eclipse-cs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a pretty printed representation of the document as a byte array.
 * 
 * @param document
 *          the document
 * @return the document as a byte array (UTF-8)
 * @throws IOException
 *           Exception while serializing the document
 */
public static byte[] toByteArray(Document document) throws IOException {

  ByteArrayOutputStream byteOut = new ByteArrayOutputStream(512);

  // Pretty print the document to System.out
  OutputFormat format = OutputFormat.createPrettyPrint();
  XMLWriter writer = new XMLWriter(byteOut, format);
  writer.write(document);

  return byteOut.toByteArray();
}
 
Example 15
Source File: XmlUtil.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void saveDocument(Document document, File xmlFile) throws IOException {
    @Cleanup
    Writer osWrite = new OutputStreamWriter(new FileOutputStream(xmlFile),StringUtil.UTF_8);// 创建输出流
    OutputFormat format = OutputFormat.createPrettyPrint(); // 获取输出的指定格式
    format.setEncoding(document.getXMLEncoding());  
    format.setNewLineAfterDeclaration(false);//解决声明下空行问题  
    
    format.setEncoding(StringUtil.UTF_8);// 设置编码 ,确保解析的xml为UTF-8格式
    @Cleanup
    XMLWriter writer = new XMLWriter(osWrite, format);// XMLWriter
    writer.write(document);// 把document写入xmlFile指定的文件(可以为被解析的文件或者新创建的文件)
    writer.flush();
}
 
Example 16
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 17
Source File: JUnitFormatter.java    From validatar with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * Writes out the report for the given testSuites in the JUnit XML format.
 */
@Override
public void writeReport(List<TestSuite> testSuites) throws IOException {
    Document document = DocumentHelper.createDocument();

    Element testSuitesRoot = document.addElement(TESTSUITES_TAG);

    // Output for each test suite
    for (TestSuite testSuite : testSuites) {
        Element testSuiteRoot = testSuitesRoot.addElement(TESTSUITE_TAG);
        testSuiteRoot.addAttribute(TESTS_ATTRIBUTE, Integer.toString(testSuite.queries.size() + testSuite.tests.size()));
        testSuiteRoot.addAttribute(NAME_ATTRIBUTE, testSuite.name);

        for (Query query : testSuite.queries) {
            Element queryNode = testSuiteRoot.addElement(TESTCASE_TAG).addAttribute(NAME_ATTRIBUTE, query.name);
            if (query.failed()) {
                String failureMessage = StringUtils.join(query.getMessages(), NEWLINE);
                queryNode.addElement(FAILED_TAG).addCDATA(failureMessage);
            }
        }
        for (Test test : testSuite.tests) {
            Element testNode = testSuiteRoot.addElement(TESTCASE_TAG).addAttribute(NAME_ATTRIBUTE, test.name);
            if (test.failed()) {
                Element target = testNode;
                if (test.isWarnOnly()) {
                    testNode.addElement(SKIPPED_TAG);
                } else {
                    target = testNode.addElement(FAILED_TAG);
                }
                target.addCDATA(NEWLINE + test.description + NEWLINE + StringUtils.join(test.getMessages(), NEWLINE));
            }
        }
    }

    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileWriter(outputFile), format);
    writer.write(document);
    writer.close();
}
 
Example 18
Source File: TestTool.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 获取对应元素的XML文本文件的字节内容
 *
 * @param element 元素
 * @return 字节内容
 */
public static byte[] xmlByte(Element element) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        XMLWriter writerToSout = new XMLWriter(out, FORMAT);
        writerToSout.write(element);
        writerToSout.flush();
        return out.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 19
Source File: SolverInfo.java    From unitime with Apache License 2.0 5 votes vote down vote up
public void setValue(Document document) {
	try {
		if (document == null) {
			setData(null);
		} else {
			 ByteArrayOutputStream bytes = new ByteArrayOutputStream();
             XMLWriter writer = new XMLWriter(new GZIPOutputStream(bytes),OutputFormat.createCompactFormat());
             writer.write(document);
             writer.flush(); writer.close();
             setData(bytes.toByteArray());
		}
	} catch (IOException e) {
		throw new HibernateException(e.getMessage(),e);
	}
}
 
Example 20
Source File: XmlUtil.java    From mybatis-daoj with Apache License 2.0 3 votes vote down vote up
/**
 * 将XML文档写入指定的文件.
 *
 * @param document XML文档
 * @param fileName 文件名
 * @param format   输出格式, 参考常量XmlUtil.FORMAT_GBK_PRETTY,
 *                 XmlUtil.FORMAT_UTF_PRETTY等
 * @throws java.io.IOException
 */
public static void write(Document document, String fileName, OutputFormat format) throws IOException {

    XMLWriter writer = new XMLWriter(new FileWriter(fileName), format);
    writer.write(document);
    writer.flush();
    writer.close();
}