XmlUtil

package util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


import entity.Employee;

public class XmlUtilW {
			
	//读取xml里的emp所有数据
	public List<Employee> readXml() throws Exception{
		Document doc = getDocument();
		Element e = doc.getDocumentElement();
		List<Employee> list = new ArrayList<Employee>();
		NodeList nodelist = e.getElementsByTagName("emp");
		for(int i=0;i<nodelist.getLength();i++){
			 Node node = nodelist.item(i);
			 NodeList nodeList2 = node.getChildNodes();
			 Employee emp = new Employee();
			 for(int j=0;j<nodeList2.getLength();j++){
				 Node cn = nodeList2.item(j);
				 String nodestr = cn.getNodeName();
				 String tempstr = cn.getTextContent().trim();
				 if(nodestr.equals("id")){
					 emp.setId(Integer.parseInt(tempstr));
				 }
				 if(nodestr.equals("name")){
					 emp.setName(tempstr);
				 }
				 if(nodestr.equals("age")){
					 emp.setAge(Integer.parseInt(tempstr));
				 }
			 }
			 list.add(emp);
		}
		return list;
	}
	
	//增加一个emp
	public void writeXml(Employee emp) throws Exception{
		Document doc = getDocument();
		Element root = doc.getDocumentElement();
		Element empE = doc.createElement("emp");
		Element id = doc.createElement("id");
		id.setTextContent(emp.getId().toString());
		Element name = doc.createElement("name");
		name.setTextContent(emp.getName());
		Element age = doc.createElement("age");
		age.setTextContent(emp.getAge().toString());
		root.appendChild(empE);
		empE.appendChild(id);
		empE.appendChild(name);
		empE.appendChild(age);
		saveXml(doc);
	}
	
	//删除xml里的一条emp记录
	public void deleteXml(Integer id)throws Exception{
		Document doc = getDocument();
		Element e = doc.getDocumentElement();
		NodeList nodelist = e.getElementsByTagName("emp");
		for(int i=0;i<nodelist.getLength();i++){
			Node node = nodelist.item(i);
			NodeList cNL =node.getChildNodes();
			for(int j=0;j<cNL.getLength();j++){
				Node cn = cNL.item(j);
				String tempstr = cn.getTextContent().trim();
				if(tempstr.equals(id.toString())){
					cn.getParentNode().getParentNode().removeChild(node);
					break;
				}
			}
		}
		saveXml(doc);
	}
	
	//更新emp信息
	public void updateXml(Employee emp) throws Exception{
		Document doc = getDocument();
		Element e = doc.getDocumentElement();
		NodeList empsNodeList = e.getElementsByTagName("emp");
		for(int i=0;i<empsNodeList.getLength();i++){
			Node empNode = empsNodeList.item(i);
			NodeList empEleList = empNode.getChildNodes();
			for(int j=0;j<empEleList.getLength();j++){
				Node node = empEleList.item(j);
				String tempstr = node.getTextContent().trim();
				if(tempstr.equals(emp.getId().toString())){
					NodeList upEleList = empNode.getChildNodes();
					for(int k=0;k<upEleList.getLength();k++){
						Node upNode = upEleList.item(k);
						String nodestr = upNode.getNodeName();
						if(nodestr.equals("id")){
							upNode.setTextContent(emp.getId().toString());
						}
						if(nodestr.equals("age")){
							upNode.setTextContent(emp.getAge().toString());
						}
						if(nodestr.equals("name")){
							upNode.setTextContent(emp.getName());
						}
					}
				}
			}
			saveXml(doc);
		}
	}
	
//	根据id找到对应的emp
	public Employee findById(Integer id){
		try {
			List<Employee> emps = readXml();
			for (Employee employee : emps) {
				if(employee.getId() == id){
					return employee;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	//保存xml
	private void saveXml(Document document) throws Exception{
		 TransformerFactory tFactory = TransformerFactory.newInstance();// 创建XML输出工厂
		 Transformer transformer = tFactory.newTransformer();// 创建XML输出对象
		 DOMSource source = new DOMSource(document);// 源对象
		 String path = XmlUtilW.class.getClassLoader().getResource("employee.xml").getPath();
//		 String path = "D:/MyEclipse7/workspace/.metadata/.plugins/com.genuitec.eclipse.easie.tomcat.myeclipse/tomcat/webapps/webxml/WEB-INF/classes/employee.xml";
		 StreamResult result = new StreamResult(new File(path));// 目标对象
		 transformer.transform(source, result);
	}
	
	private Document getDocument() throws Exception {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setIgnoringElementContentWhitespace(true);
		DocumentBuilder parser = factory.newDocumentBuilder();
		 String path=XmlUtilW.class.getClassLoader().getResource("employee.xml").getPath();
//		 System.out.println("getDocument:" + path);
		Document document = parser.parse(new File(path));
		return document;
	}
	
	
	public static void main(String[] args) throws Exception {
//		String path = XmlUtilW.class.getClassLoader().getResource("employee.xml").getPath();
		XmlUtilW xmlUtil = new XmlUtilW();
		
		//找出一个emp
//		Employee employee1 = xmlUtil.findById(1);
//		System.out.println(employee1.getId()+","+employee1.getName()+","+employee1.getAge());
//		System.out.println("---------");
		
//		读取xml的所有emp
//		List<Employee> emps = xmlUtil.readXml();
//		for (Employee employee : emps) {
//			System.out.println(employee.getId()+","+employee.getName()+","+employee.getAge());
//		}
			
//		删除一个emp
//		xmlUtil.deleteXml(3);
		
		
//		修改一个emp
//		xmlUtil.updateXml(emp);
		
		Employee emp = new Employee();
		emp.setId(4);
		emp.setAge(22);
		emp.setName("abc");
//		写入一个emp
		xmlUtil.writeXml(emp);
		
	}
}

 

你可能感兴趣的:(eclipse,tomcat,xml,MyEclipse,J#)