dom4j XML Read and write modification operations

Source: Internet
Author: User
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import java.util.ArrayList;
Import Java.util.HashSet;
Import Java.util.Iterator;
Import java.util.List;

Import Java.util.Set;
Import Org.apache.log4j.Logger;
Import org.dom4j.Document;
Import org.dom4j.DocumentException;
Import Org.dom4j.DocumentHelper;
Import org.dom4j.Element;
Import Org.dom4j.Node;
Import Org.dom4j.io.OutputFormat;
Import Org.dom4j.io.SAXReader;


Import Org.dom4j.io.XMLWriter;
	
	public class Persondao {private static final Logger Logger = Logger.getlogger (Persondao.class);
	
	Private Document Doc;
	Private String Xmlpath = Thread.CurrentThread (). Getcontextclassloader (). GetResource ("Persons.xml"). GetPath ();
	Private static final String error = "Error";
	
	Private static final String success = "Success";
	
	private static Persondao Persondao = new Persondao ();
	Private Persondao () {getpersondata ();
	Public Persondao getinstance () {return persondao; /** * Get people configuration Data * @return */Private document Getpersondata () {if (doc = = null) {//If Doc is empty, read file Inputxml = new files (xmlpath)
			;
			Saxreader Saxreader = new Saxreader ();
			try {doc = Saxreader.read (inputxml); catch (Documentexception e) {logger.error ("Error reading personnel profile.")
			", e);
	} return doc; /** * Update Personnel configuration * @return/private synchronized String Writepersondata () {//todo Want to add backup recovery mechanism try {FILEOUTP
			Utstream outputstream = new FileOutputStream (Xmlpath);
            OutputFormat format = Outputformat.createprettyprint ();
			Format.setencoding ("UTF-8");
			XMLWriter XMLWriter = new XMLWriter (Outputstream,format);
			Xmlwriter.write (Getpersondata ());
		Xmlwriter.close (); catch (IOException e) {logger.error ("Update the personnel Profile error.")
			", e);
		return error;
	return success; /** * To determine if the user name exists * @param name person * @return/public boolean isnameexist (String name) {//Get the name of all people list& Lt
		node> nodes = doc.selectnodes ("Persons/person/name"); Check the name of the new personWhether there is a set<string> Set = new hashset<string> ();
		for (int i = 0; i < nodes.size (); i++) {Set.add (Nodes.get (i) getText ());
		} if (Set.contains (name)) {return true;
	return false;
		/** * Additional staff * @param PERSONVO Staff Information * @return/public synchronized String Addperson (Personvo personvo) {
			The name cannot be empty if (personvo.getname () = = null) {logger.error ("person's name is null");
		return "Name.isnull";
				try {if (Isnameexist (Personvo.getname ())) {Logger.error ("name exist");
			return "Name.exist";
			///Create person node Element person = documenthelper.createelement (' person ');
				The following is the addition of the attribute node name, email, phone, and so on if (personvo.getname ()!= null) {Element name = documenthelper.createelement ("name");
				Name.settext (Personvo.getname ());
			Person.add (name);
				} if (Personvo.getphone ()!= null) {Element phone = documenthelper.createelement ("Phone");
				Phone.settext (Personvo.getphone ());
			Person.add (phone); } if (perSonvo.getemail ()!= null) {Element email = documenthelper.createelement ("email");
				Email.settext (Personvo.getemail ());
			Person.add (email);
				} if (personvo.getcomment ()!= null) {Element comment = documenthelper.createelement ("comment");
				Comment.settext (Personvo.getcomment ());
			Person.add (comment);
			} doc.getrootelement (). Add (person);
			Logger.info ("added XML content:" + doc.asxml ());
			Update to file String result = Writepersondata ();
		return result;
			catch (RuntimeException e) {logger.error ("exception occurred while adding personnel", e);
		return "Addperson.error"; /** * Modify personnel information, modify information other than the name * @param PERSONVO Personnel information * @return/public synchronized String Updateperson (Perso
			Nvo personvo) {//name cannot be empty if (personvo.getname () = = null) {logger.error ("person ' s name is null");
		return "Name.isnull";
		} list<element> List = Doc.selectnodes ("Persons/person/name");
		Element nameelement = null; Locate the name node for the person you want to modify for (int i = 0; i < list.size (); i++) {if (LIST.get (i). GetText (). Equals (Personvo.getname ())) {nameelement = List.get (i);
			Break
		}//If not found, indicates that the person does not exist if (nameelement = = null) {return "person.notexist";
		//Get the parent node, the person node Element parent = Nameelement.getparent ();
		If the node exists, modify the attribute, and if the node does not exist, add the node Element phone = parent.element ("Phone");
			if (phone = = null) {phone = documenthelper.createelement ("Phone");
			Phone.settext (Personvo.getphone ());
		Parent.add (phone);
		}else {Phone.settext (Personvo.getphone ());
		Element email = parent.element ("email");
			if (email = = NULL) {email = documenthelper.createelement ("email");
			Email.settext (Personvo.getemail ());
		Parent.add (email);
		}else {Email.settext (Personvo.getemail ());
		Element comment = parent.element ("comment");
			if (comment = = null) {comment = documenthelper.createelement ("comment");
			Comment.settext (Personvo.getcomment ());
		Parent.add (comment);
		}else {Comment.settext (personvo.getcomment ()); } logger.info ("ModifiedDocumentation: \ r \ n "+ doc.asxml ());
		String result = Writepersondata ();
	return result; /** * List all personnel information * @return/public List listpersons () {list<personvo> list = new Arraylist<personv
		O> ();
		Element root = Doc.getrootelement ();
		Iterator<element> it = Root.elementiterator ();
			while (It.hasnext ()) {element element = It.next ();
			String name = Element.selectsinglenode ("name"). GetText ();
			String phone = element.selectsinglenode ("Phone"). GetText ();
			String email = element.selectsinglenode ("email"). GetText ();
			
			String comment = Element.selectsinglenode ("comment"). GetText ();
			Personvo personvo = new Personvo ();
			Personvo.setcomment (comment);
			Personvo.setemail (email);
			Personvo.setname (name);
			Personvo.setphone (phone);
			List.add (PERSONVO);
		Logger.info ("Personvo info:" +personvo); 
	} return list; /** * Delete person * @param name * @return/Public String Deleteperson (string name) {//name cannot be null if (name = = Nu ll) {LoggeR.error ("person ' s name is null");
		return "Name.isnull";
		} list<element> List = Doc.selectnodes ("Persons/person/name");
		Element nameelement = null; Locate the name node for the person you want to modify for (int i = 0; i < list.size (); i++) {if list.get (i) GetText (). Equals (name)) {Nameelement
				= List.get (i);
			Break
		}//If not found, indicates that the person does not exist if (nameelement = = null) {return "person.notexist";
		//Get the parent node, the person node Element parent = Nameelement.getparent ();
		Boolean flag = Doc.getrootelement (). Remove (parent);//remove can only delete the immediate node logger.info ("Delete result:" + flag);
		Logger.info ("deleted document: \ r \ n" + doc.asxml ());
		if (!flag) {return "delete.failure";
		String result = Writepersondata ();
	return result;
		public static void Main (string[] args) {Persondao Persondao = new Persondao ();
		Personvo personvo = new Personvo ();
		Personvo.setname ("Zhang 34");
		Personvo.setphone ("1584");
		Personvo.setemail ("123email");
		Personvo.setcomment ("123comment"); System.out.println (Persondao.deleteperSon ("Zhang 34")) }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.