dom4j 写简单XML文件

 
package com.zeph.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

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

public class AnalysisXML {
	Document document = null;
	XMLWriter xmlWriter = null;

	public AnalysisXML() {
		document = DocumentHelper.createDocument();
	}

	public void writeXML() {
		// 一个元素中应该包含元素内容或者文本内容,否则不是对称元素
		Element shopElement = document.addElement("SHOP");
		shopElement.addComment("This is a XML root element");

		Element bookElement1 = shopElement.addElement("BOOK");
		bookElement1.addAttribute("id", "1");
		Element titleElement1 = bookElement1.addElement("TITLE");
		titleElement1.setText("Android Unleashed");
		Element priceElement1 = bookElement1.addElement("PRICE");
		priceElement1.setText("69 Yuan");
		Element publishElment1 = bookElement1.addElement("PUBLISH");
		publishElment1.setText("China Machine Press");

		Element bookElement2 = shopElement.addElement("BOOK");
		bookElement2.addAttribute("id", "2");
		Element titleElement2 = bookElement2.addElement("TITLE");
		titleElement2.setText("Thinking in Java");
		Element priceElement2 = bookElement2.addElement("PRICE");
		priceElement2.setText("108 Yuan");
		Element publishElement2 = bookElement2.addElement("PUBLISH");
		publishElement2.setText("China Machine Press");

		try {
			xmlWriter = new XMLWriter(new FileWriter(new File("D:/dom4j.xml")));
			xmlWriter.write(document);
			xmlWriter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String args[]) {
		AnalysisXML analysisXML = new AnalysisXML();
		analysisXML.writeXML();
	}
}

你可能感兴趣的:(java,xml,android,String,File,Class)