DOM4J

import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;

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

public class XMLParser {
	public static void main(String[] args) throws IOException {
		//第一种方式
//		Document document = DocumentHelper.createDocument();
//		Element root = DocumentHelper.createElement("student");
//		document.setRootElement(root);
		
		Element root = DocumentHelper.createElement("student");
		Document document = DocumentHelper.createDocument(root);
		root.addAttribute("name", "孙小毛");
		Element helloElement = root.addElement("hello");
		Element worldElement = root.addElement("world");
		helloElement.addText("hello");
		worldElement.addText("world");
		helloElement.addAttribute("age", "10");
		
		XMLWriter xmlWriter = new XMLWriter();
		OutputFormat format = new OutputFormat("    ", true);
		XMLWriter xmlWriter2 = new XMLWriter(new FileOutputStream("student.xml"), format);
		XMLWriter xmlWriter3 = new XMLWriter(new FileWriter("student2.xml"), format);
		xmlWriter3.write(document);
		xmlWriter3.flush();
		xmlWriter3.close();
		xmlWriter2.write(document);
		xmlWriter.write(document);
	}
}

 

你可能感兴趣的:(dom4j)