JAVA利用dom4j创建和生产XML文件

look code:

 

package com.JsonandXML;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class CrearteAndOutputXML {
	public static void main(String[] args) {
		XML1();
		XML2();
	}
//简化版
	public static void XML1() {
		//Create XML String 
		Document documentXML = DocumentHelper.createDocument();
		Element employees = documentXML.addElement("employees");
		Element employee = employees.addElement("employee");
		Element name = employee.addElement("name");
		name.setText("ddvip");
		Element sex = employee.addElement("sex");
		sex.setText("m");
		Element age = employee.addElement("age");
		age.setText("29");

		// output XML File
		try {
			OutputFormat of = new OutputFormat();
			of.setIndent(true);
			of.setNewlines(true);
			Writer fileWriter = new FileWriter("d:/test.xml");
			XMLWriter xmlWriter = new XMLWriter(fileWriter, of);
			xmlWriter.write(documentXML);
			xmlWriter.close();
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}
	
	//升级版
	public static void XML2() {
		//Create XML String 
		Document documentXML = DocumentHelper.createDocument();
		Element employees = documentXML.addElement("employees");
		employees.addAttribute("attaribut", "name,sex,age");

		
		Element employee = employees.addElement("employee");
		Element name = employee.addElement("name");
		name.setText("ddvip");
		Element sex = employee.addElement("sex");
		sex.setText("m");
		Element age = employee.addElement("age");
		age.setText("29");

		Element employee_2 = employees.addElement("employee");
		employee_2.addAttribute("single", "yes");
		Element name_2 = employee_2.addElement("name");
		name_2.setText("jacksyc");
		Element sex_2 = employee_2.addElement("sex");
		sex_2.setText("man");
		Element age_2 = employee_2.addElement("age");
		age_2.addAttribute("year", "80");
		age_2.setText("23");

		// output XML File
		try {
			OutputFormat of = new OutputFormat();
			of.setIndent(true);
			of.setNewlines(true);
			Writer fileWriter = new FileWriter("d:/test2.xml");
			XMLWriter xmlWriter = new XMLWriter(fileWriter, of);
			xmlWriter.write(documentXML);
			xmlWriter.close();
		} catch (IOException e) {

			System.out.println(e.getMessage());
		}
	}
	
	
}

 

你可能感兴趣的:(dom4j)