DOM4J方式生成xml文档

private void creatXML() {
		//创建Document对象,代表整个xml文档
		Document document = DocumentHelper.createDocument();
		//2.创建根节点rss
		Element rss = document.addElement("rss");
		//3.向rss节点中添加version属性
		rss.addAttribute("version",	"2.0");
		//4.生成子节点及节点内容
		Element channel = rss.addElement("channel");
		Element title = channel.addElement("title");
		title.setText("<<>>国内最新新闻");
		//5.设置生成xml文件格式(利用OutputFormat的creatPrettyPrint()方法设置)
		OutputFormat format = OutputFormat.createPrettyPrint();
		//设置编码格式
		format.setEncoding("GBK");
		//6.生成文件
		File file = new File("src/res/rssnews.xml");
		XMLWriter writer;
		try {
			//先创建XMLWriter对象
			writer = new XMLWriter(new FileOutputStream(file), format);
			//设置是否转义符号,默认值为true,代表转义
			writer.setEscapeText(false);
		//利用XMLWriter的write方法传入Document类型对象
			writer.write(document);
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

猜你喜欢

转载自blog.csdn.net/weixin_42545898/article/details/88063157