XML文件作业---实现简单的通讯录功能(XML作为简单数据库)(总结)

前端之家收集整理的这篇文章主要介绍了XML文件作业---实现简单的通讯录功能(XML作为简单数据库)(总结)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

XML文件作业---实现简单的通讯录功能(XML作为简单数据库

实现功能:对XML文件进行信息的增删查改;

项目整体视图:

对象类:Contact.java

package Test;
/*
 * 联系人实体对象
 */
public class Contact {
	private String id;
	private String name;
	private String gender;
	private int age;
	private String phone;
	private String email;
	private String qq;
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getQq() {
		return qq;
	}
	public void setQq(String qq) {
		this.qq = qq;
	}
	@Override
	public String toString() {
		return "Contact [id=" + id + ",mame=" + name + ",gender=" + gender
				+ ",age=" + age + ",phone=" + phone + ",email=" + email
				+ ",qq=" + qq + "]";
	}
}

主程序:MainProgram.java

package Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

public class MainProgram {
	@SuppressWarnings("null")
	public static void main(String[] args) {
		try {			
			//接收用户输入的命令
//			Scanner scanner = new Scanner(System.in);
//			String command = scanner.next();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			ContactOperator operator = new ContactOperatorImpl();
			while(true) {
				//1.看到菜单
				printMenu();
				
				//2.接收用户输入命令
				String command = br.readLine();
			
				//3.根据用户输入执行不同的操作
				if("1".equals(command)) {
					//添加联系人
					//获取用户输入的数据
					Contact contact = new Contact();
					//获取ID
					System.out.println("请输入编号:");
					String id = br.readLine();
					//获取姓名
					System.out.println("请输入姓名");
					String name = br.readLine();
					//获取性别
					System.out.println("请输入性别");
					String gender = br.readLine();
					//获取年龄
					System.out.println("请输入年龄");
					String age = br.readLine();
					//获取电话
					System.out.println("请输入手机号");
					String phone = br.readLine();
					//获取邮箱
					System.out.println("请输入邮箱");
					String email = br.readLine();
					//获取QQ
					System.out.println("请输入QQ");
					String qq = br.readLine();
					
					//封装到对象
					contact.setId(id);
					contact.setName(name);
					contact.setAge(Integer.parseInt(age));
					contact.setGender(gender);
					contact.setEmail(email);
					contact.setPhone(phone);
					contact.setQq(qq);
					
					//调用添加联系人的方法
					operator.addContact(contact);
				} else if("2".equals(command)) {
					//修改联系人
					Contact contact = new Contact();
					//获取ID
					System.out.println("请输入需要修改的编号:");
					String id = br.readLine();
					//获取姓名
					System.out.println("请输入修改后的姓名");
					String name = br.readLine();
					//获取性别
					System.out.println("请输入修改后的性别");
					String gender = br.readLine();
					//获取年龄
					System.out.println("请输入修改后的年龄");
					String age = br.readLine();
					//获取电话
					System.out.println("请输入修改后的手机号");
					String phone = br.readLine();
					//获取邮箱
					System.out.println("请输入修改后的邮箱");
					String email = br.readLine();
					//获取QQ
					System.out.println("请输入修改后的QQ");
					String qq = br.readLine();
					
					//封装到对象
					contact.setId(id);
					contact.setName(name);
					contact.setAge(Integer.parseInt(age));
					contact.setGender(gender);
					contact.setEmail(email);
					contact.setPhone(phone);
					contact.setQq(qq);
					
					//调用修改联系人的方法
					operator.updateContact(contact);
				} else if("3".equals(command)) {
					//删除联系人
					System.out.println("请输入你要删除的编号:");
					String id = br.readLine();
					
					//调用删除联系人的方法
					operator.deleteContact(id);
				} else if("4".equals(command)) {
					//查找所有联系人
					List<Contact> list = operator.findAll();
					//打印输出
					for(Contact con : list) {
						System.out.println(con);
					}
					
				} else if("Q".equals(command)) {
					
					break;
				} else {
					System.out.println("输入有错误");
				}
			}
			
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	private static void printMenu() {
		//1.看到菜单
		System.out.println("======================");
		System.out.println("[1]添加联系人");
		System.out.println("[2]修改联系人");
		System.out.println("[3]删除联系人");
		System.out.println("[4]查看所有联系人");
		System.out.println("[Q]退出系统");
		System.out.println("=======================");
	}
}

定义联系人存放的方法的接口:ContactOperator.java

package Test;

import java.util.List;

/*
 * 该接口用于存放联系人相关操作方法
 */
public interface ContactOperator {
	public void addContact(Contact contact);//添加联系人
	public void updateContact(Contact contact);//修改联系人
	public void deleteContact(String id);//删除联系人
	public List<Contact> findAll();//查询所有联系人
}

上面接口方法的实现类:ContactOperatorImpl.java

package Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

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 ContactOperatorImpl implements ContactOperator {
	
	public void addContact(Contact contact)  {
		try {
			/*
			 * 需求:把contact对象保存到XML文件中
			 */
			File file = new File("e:/contact.xml");
			Document doc = null;
			Element rootElem = null;
			if(!file.exists()) {
				//如果没有XML文件,则创建XML文件
				doc = DocumentHelper.createDocument();
				//创建根标签
				rootElem = doc.addElement("contactList");
			} else {
				//如果有XML文件,则读取XML文件
				doc = new SAXReader().read(file);
				//读取根标签
				rootElem = doc.getRootElement();
			}
			
			//添加contact标签
			Element contactElem = rootElem.addElement("contact");
			
			contactElem.addAttribute("id",contact.getId());
			contactElem.addElement("name").setText(contact.getName());
			contactElem.addElement("gender").setText(contact.getGender());
			contactElem.addElement("age").setText(contact.getAge()+"");
			contactElem.addElement("phone").setText(contact.getPhone());
			contactElem.addElement("email").setText(contact.getEmail());
			contactElem.addElement("qq").setText(contact.getQq());
			
			//把Document写到XML文件
			XMLUtil.Writexml(doc);
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} 
	}

	public void updateContact(Contact contact) {
		/*
		 * 修改id值为2的联系人
		 * 1)查询id值为2的contact标签
		 * 2)修改contact标签中的内容
		 */
		try {
			//1.读取XML文件
			Document doc = XMLUtil.getDocument();
			Element contactElem = (Element)doc.selectSingleNode("//contact[@id='"+contact.getId()+"']");
			
			//2.修改contact标签中的内容
			contactElem.element("name").setText(contact.getName());
			contactElem.element("gender").setText(contact.getGender());
			contactElem.element("age").setText(contact.getAge()+"");
			contactElem.element("email").setText(contact.getEmail());
			contactElem.element("qq").setText(contact.getQq());
			
			//把Document写到XML文件
			XMLUtil.Writexml(doc);
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public void deleteContact(String id) {
		
		try {
			//1.读取XML文件
			Document doc = XMLUtil.getDocument();
			//2.查询需要删除id的contact
			Element contactElem = (Element)doc.selectSingleNode("//contact[@id='"+id+"']");
			//3.删除标签
			contactElem.detach();
			//4.把Document写到XML文件
			XMLUtil.Writexml(doc);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public List<Contact> findAll() {
		//1.读取XML文件
		Document doc = XMLUtil.getDocument();
		//2.创建List对象
		List<Contact> list = new ArrayList<Contact>();
		//3.读取contact标签
		List<Element> conList = (List<Element>)doc.selectNodes("//contact");
		for(Element e : conList) {
			//创建Contact对象
			Contact c = new Contact();
			c.setId(e.attributeValue("id"));
			c.setName(e.elementText("name"));
			c.setGender(e.elementText("gender"));
			c.setAge(Integer.parseInt(e.elementText("age")));
			c.setEmail(e.elementText("email"));
			c.setPhone(e.elementText("phone"));
			c.setQq(e.elementText("qq"));
			//把contact对象放到list中
			list.add(c);
		}
		return list;
	}

}

对XML文件进行操作的方法实现类:XMLUtil.java

package Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

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

public class XMLUtil {
	
	/*
	 * 用于读取XML文件
	 */
	public static Document getDocument() {
		try {
			Document doc = new SAXReader().read(new File("e:/contact.xml"));
			return doc;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
	
	/*
	 * 写出XML文件
	 */
	public static void Writexml(Document doc) {
		try {
			//3.把Document写到XML文件
			FileOutputStream out = new FileOutputStream("e:/contact.xml");
			//书写格式(优美的格式)
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			XMLWriter writer = new XMLWriter(out,format);
			writer.write(doc);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		} 
	}
}

接口方法实现的测试类:TestContactOperatorImpl.java

package Test;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

/*
 * 联系人操作实现的测试类
 */
public class TestContactOperatorImpl {
	
	ContactOperator operator = null;
	/*
	 * 初始化对象实例
	 */
	@Before
	public void init() {
		operator = new ContactOperatorImpl();
	}
	@Test
	public void testAddContact() {
		Contact contact = new Contact();
		contact.setId("4");
		contact.setName("sb");
		contact.setGender("男");
		contact.setPhone("2333");
		contact.setEmail("er");
		contact.setQq("9777");
		operator.addContact(contact);
	}
	
	@Test
	public void testUpdateContact() {
		Contact contact = new Contact();
		contact.setId("3");//修改的ID值
		contact.setName("李四");
		contact.setGender("男");
		contact.setAge(20);
		contact.setPhone("2333");
		contact.setEmail("er");
		contact.setQq("9777");
		operator.updateContact(contact);
	}
	
	@Test
	public void testDeleteContact() {
		operator.deleteContact("2");
	}
	
	@Test
	public void testFindAll() {
		List<Contact> list = operator.findAll();
		for(Contact contact : list) {
			System.out.println(contact);
		}
	}
}

猜你在找的XML相关文章