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

The following examples show how to use org.dom4j.io.OutputFormat#setNewlines() . These examples are extracted from open source projects. 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 Project: onedev   File: VersionedXmlDoc.java    License: MIT License 6 votes vote down vote up
public String toXML(boolean pretty) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	try {
		OutputFormat format = new OutputFormat();
		format.setEncoding(StandardCharsets.UTF_8.name());
		if (pretty) {
			format.setIndent(true);
			format.setIndentSize(4);
	        format.setNewlines(true);
		} else {
	        format.setIndent(false);
	        format.setNewlines(false);
		}
		new XMLWriter(baos, format).write(getWrapped());
		return baos.toString(StandardCharsets.UTF_8.name());
	} catch (Exception e) {
		throw ExceptionUtils.unchecked(e);
	}
}
 
Example 2
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 3
public static String toString(final Element el, final boolean prettyFormat)
{
  if (el == null) {
    return "";
  }
  final StringWriter out = new StringWriter();
  final OutputFormat format = new OutputFormat();
  if (prettyFormat == true) {
    format.setNewlines(true);
    format.setIndentSize(2);
  }
  final XMLWriter writer = new XMLWriter(out, format);
  String result = null;
  try {
    writer.write(el);
    result = out.toString();
    writer.close();
  } catch (final IOException ex) {
    log.error(ex.getMessage(), ex);
  }
  return result;
}
 
Example 4
Source Project: EasyML   File: WFGraph.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String args[]){

		Namespace rootNs = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri
		QName rootQName = QName.get("workflow-app", rootNs); // your root element's name
		Element workflow = DocumentHelper.createElement(rootQName);
		Document doc = DocumentHelper.createDocument(workflow);
		
		workflow.addAttribute("name", "test");
		Element test = workflow.addElement("test");
		test.addText("hello");
				OutputFormat outputFormat = OutputFormat.createPrettyPrint();
				outputFormat.setEncoding("UTF-8");
				outputFormat.setIndent(true); 
				outputFormat.setIndent("    "); 
				outputFormat.setNewlines(true); 
		try {
			StringWriter stringWriter = new StringWriter();
			XMLWriter xmlWriter = new XMLWriter(stringWriter);
			xmlWriter.write(doc);
			xmlWriter.close();
			System.out.println( doc.asXML() );
			System.out.println( stringWriter.toString().trim());

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
 
Example 5
Source Project: EasyML   File: WFGraph.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Transform the Graph into an workflow xml definition
 * @param jobname the job name of Oozie job, can't be null
 * @return workflow xml
 */
public String toWorkflow(String jobname) {
	Namespace xmlns = new Namespace("", "uri:oozie:workflow:0.4"); // root namespace uri
	QName qName = QName.get("workflow-app", xmlns); // your root element's name
	Element workflow = DocumentHelper.createElement(qName);
	Document xmldoc = DocumentHelper.createDocument(workflow);
	// Create workflow root
	workflow.addAttribute("xmlns", "uri:oozie:workflow:0.4");
	// <workflow-app name='xxx'></workflow-app>
	if (jobname == null || "".equals(jobname))
		workflow.addAttribute("name", "Not specified");
	else
		workflow.addAttribute("name", jobname);

	Queue<NodeDef> que = new LinkedList<NodeDef>();
	que.add(start);

	while (!que.isEmpty()) {
		NodeDef cur = que.remove();

		cur.append2XML(workflow);

		for (NodeDef toNode : cur.getOutNodes()) {
			toNode.delInNode(cur);
			if (toNode.getInDegree() == 0)
				que.add(toNode);
		}
	}

	// Set XML document format
	OutputFormat outputFormat = OutputFormat.createPrettyPrint();
	// Set XML encoding, use the specified encoding to save the XML document to the string, it can be specified GBK or ISO8859-1
	outputFormat.setEncoding("UTF-8");
	outputFormat.setSuppressDeclaration(true); // Whether generate xml header
	outputFormat.setIndent(true); // Whether set indentation
	outputFormat.setIndent("    "); // Implement indentation with four spaces
	outputFormat.setNewlines(true); // Set whether to wrap

	try {
		// stringWriter is used to save xml document
		StringWriter stringWriter = new StringWriter();
		// xmlWriter is used to write XML document to string(tool)
		XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);
		
		// Write the created XML document into the string
		xmlWriter.write(xmldoc);

		xmlWriter.close();

		System.out.println( stringWriter.toString().trim());
		// Print the string, that is, the XML document
		return stringWriter.toString().trim();

	} catch (Exception ex) {
		ex.printStackTrace();
	}
	return null;
}
 
Example 6
public static void parseXML(String filePath) {
	// InputStream is = null;
	// try {
	// is = new InputStreamReader(new FileInputStream(new File(filePath)));
	// } catch (FileNotFoundException e1) {
	// e1.printStackTrace();
	// MyLogger.logger.error(e1.getMessage());
	// }
	SAXReader saxReader = new SAXReader();
	Document document = null;
	try {
		document = saxReader.read(new BufferedReader(new InputStreamReader(new FileInputStream(new File(filePath)),
				EncodingUtil.CHARSET_UTF8)));
	} catch (DocumentException | UnsupportedEncodingException | FileNotFoundException e1) {
		e1.printStackTrace();
		MyLogger.logger.error(e1.getMessage());
	}
	// Element rootElement = document.getRootElement();
	// System.out.println("根节点名称:" + rootElement.getName());
	// System.out.println("根节点的属性个数:" + rootElement.attributeCount());
	// System.out.println("根节点id属性的值:" + rootElement.attributeValue("id"));
	// System.out.println("根节点内文本:" + rootElement.getText());
	// System.out.println("根节点内去掉换行tab键等字符:" + rootElement.getTextTrim());
	// System.out.println("根节点子节点文本内容:" + rootElement.getStringValue());

	// Element content = rootElement.element("Content");
	// Element paragraph = content.element("Paragraph");
	// Element sentence = paragraph.element("Sentence");

	// Element event = sentence.element("Event");
	// Element event = paragraph.element("Event");
	@SuppressWarnings("unchecked")
	List<Element> event_list = document.selectNodes("//Sentence/Event");
	@SuppressWarnings("unchecked")
	List<Element> denoter_list = document.selectNodes("//Sentence/Event/Denoter");
	Iterator<Element> denoterIter = denoter_list.iterator();
	Iterator<Element> eventIter = event_list.iterator();
	// Element para = doc.element("para");
	// Element sent = para.element("sent");
	while (denoterIter.hasNext()) {
		Element denoter = denoterIter.next();
		Element event = eventIter.next();
		String denoterValue = denoter.getTextTrim();
		for (int i = 0; i < treeSetsList.size(); i++) {
			if (treeSetsList.get(i).contains(denoterValue)) {
				String typeValue = type_value.get(i);// 获取denoter的type值
				if (0 == i) {
					// 说明是意念事件,那么这时候拿到的typeValue是Event的属性值
					event.addAttribute("type", typeValue);
					denoter.addAttribute("type", "statement");// 默认意念事件触发词的类型都是statement
					// 注意如果是意念事件的话,event的type是thoughtEvent,denoter的属性是statement
					// 只要发现了一个意念事件,那个根据原则,就应该将意念事件的关系加到文档末尾
					document.getRootElement().addElement(Annotation.THOUGHTEVENT_RELATION);
				} else {
					// 为event添加属性和值
					denoter.addAttribute("type", typeValue);
				}
			}
		}
	}
	// 这部分用来实现判断Time是不是绝对时间
	@SuppressWarnings("unchecked")
	List<Element> time_list = document.selectNodes("//Sentence/Event/Time");
	Iterator<Element> timeIter = time_list.iterator();
	while (timeIter.hasNext()) {
		Element time = timeIter.next();
		String timeValue = time.getTextTrim();
		if (isAbsTime(timeValue)) {
			time.addAttribute("type", "absTime");
		}
	}

	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(filePath), EncodingUtil.CHARSET_UTF8), format);
		writer.write(document);
		writer.close();
		// 使用common的Util包写入
		// FileWriterWithEncoding out = new FileWriterWithEncoding(new File(filePath), "UTF-8");
		// document.write(out);
		// out.flush();
		// out.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}