JAva追加削除xml


package com.fenuang.handel;

import java.io.File;
import java.io.FileOutputStream;
import java.text.AttributedCharacterIterator.Attribute;

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

public class test1 {
	public static void main(String[] args) throws Exception {
		/**
		 * 1,Read a document object or create a document
		 */

		// Read a document object
		// Document doc = new SAXReader().read(new File("./conf/test.xml"));

		// or create a document
		Document doc = DocumentHelper.createDocument();

		/**
		 * 2,To change the contents of the file object here
		 * 
		 * for instance add a label . a attribute amend(  ) attribute's value
		 * text'value delete(  ) label attribute
		 */

		/**
		 * @1 if you want to create a label you can this
		 */

		// you must to create a root label
		Element rootelement = doc.addElement("concent");

		// then you can add children label by rootelement
		Element firstChilderen = rootelement.addElement("user");

		// add attribute to label
		firstChilderen.addAttribute("id", "001");

		// add text to label
		firstChilderen.addText("fenuang");

		// amend a attribute in a label
		// first you should get a attribut's value
		Element attr = firstChilderen.addAttribute("id", "002");

		/**
		 * 3,Write to the specified folder
		 */
		FileOutputStream outfile = new FileOutputStream("e:/hello.xml");

		/**
		 * The appearance of the specified output file format
		 */
		// OutputFormat outformat = OutputFormat.createCompactFormat(); //
		// Set the output document format to compact format
		OutputFormat outformat = OutputFormat.createPrettyPrint(); // Set the
																	// output
																	// document
																	// format to
																	// format

		/**
		 * Set the output file encoding
		 */
		outformat.setEncoding("utf-8");

		/**
		 * Create write object
		 */
		XMLWriter writer = new XMLWriter(outfile);
		/**
		 * Write out the object
		 */
		writer.write(doc);
		/**
		 * Close the stream
		 */
		writer.close();

	}
}