本地文件 生成xml

package com.thtf.ezone.ezoa.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Comparator;

import org.w3c.dom.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.*;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;

public class OrderXML {

	/**
	 * @param args
	 */
	private Document xmldoc = null;
	private Element root = null;
	private String filename = null;
	private String base = null;

	public void setBase(String base) {
		this.base = new File(base).getAbsolutePath();
	}
	public OrderXML(){}
	
	public void  generXML(HttpServletRequest request ) {
		String path=request.getContextPath();
		System.out.println(path);
		OrderXML order=new OrderXML();

	 
	    order.CreateXML("D:/easyway/apache-tomcat-6.0.14/webapps/ezone/documents/share.xml", "D:/easyway/apache-tomcat-6.0.14/webapps/ezone/documents/share/文件夹");
		
	}

	public OrderXML(String filename) {
		this.filename = filename;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			factory.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = factory.newDocumentBuilder();
			xmldoc = db.parse(new File(filename));
			root = xmldoc.getDocumentElement();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	public void CreateXML(String filename,String foldername) {
		DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        try {
            factory.setIgnoringElementContentWhitespace(true);
            DocumentBuilder db=factory.newDocumentBuilder();
            Document xmldoc= db.newDocument();
            Element root=xmldoc.createElement("rootdir");
            root.setAttribute("version", "1");
//            String[] name = foldername.split("\\\\");
//            root.setAttribute("name", name[name.length - 1]);
			
            xmldoc.appendChild(root);
            File folder=new File(foldername);
           
            addNode(root,folder,xmldoc);
	        TransformerFactory transFactory=TransformerFactory.newInstance();
	        try {
	            Transformer transformer = transFactory.newTransformer();
	            transformer.setOutputProperty("encoding", "utf-8");
	            transformer.setOutputProperty("indent", "yes");
	            DOMSource source=new DOMSource();
	            source.setNode(xmldoc);
	            StreamResult result=new StreamResult();
	            try {
					result.setOutputStream(new FileOutputStream(filename));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            transformer.transform(source, result);
	        } catch (TransformerConfigurationException e) {
	            e.printStackTrace();
	        } catch (TransformerException e) {
	            e.printStackTrace();
	        }   
        }catch(Exception e){e.printStackTrace();}
	}
	public void addNode(Element node,File folder,Document xmldoc) {
		if(folder.isDirectory()){
			//目录节点
			Element child=xmldoc.createElement("dir");
			child.setAttribute("name", folder.getName());
			child.setAttribute("id", "1");
			child.setAttribute("sortid", "0");
			node.appendChild(child);
			File[] folders=folder.listFiles();
			for(File file:folders){
				addNode(child,file,xmldoc);
			}
    	}else{
    		//文件节点
    		Element child=xmldoc.createElement("file");
			child.setAttribute("name", folder.getName());
			child.setAttribute("id", "1");
			node.appendChild(child);
    	}
	}
	
	
	
	
	
	
	//目录
	public void adddir(String filename, String foldername) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			factory.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = factory.newDocumentBuilder();
			Document xmldoc = db.parse(new File(filename));
			Element root = xmldoc.getDocumentElement();
			String[] name = foldername.split("\\\\");
			String dir = getDeep2(foldername);
			 String []dirs=  dir.split("/");
			 String path = "/rootdir";
			 for(int i=0;i<dirs.length-1;i++){
				 path+="/" +dirs[i];
			 }
			Element node = (Element) selectSingleNode(path , root);
			if(node!=null){
			Element child = xmldoc.createElement("dir");
			child.setAttribute("name", name[name.length - 1]);
			child.setAttribute("id", "1");
			child.setAttribute("sortid", "0");
			node.appendChild(child);
			int id=  Integer.parseInt(root.getAttribute("version"));
			root.setAttribute("version", String.valueOf(id+1));
			}

			TransformerFactory transFactory = TransformerFactory.newInstance();
			try {
				Transformer transformer = transFactory.newTransformer();
				transformer.setOutputProperty("encoding", "utf-8");
				transformer.setOutputProperty("indent", "yes");
				DOMSource source = new DOMSource();
				source.setNode(xmldoc);
				StreamResult result = new StreamResult();
				try {
					result.setOutputStream(new FileOutputStream(filename));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				transformer.transform(source, result);
			} catch (TransformerConfigurationException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
		

	public void deldir(String filename, String foldername) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			factory.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = factory.newDocumentBuilder();
			Document xmldoc = db.parse(new File(filename));
			Element root = xmldoc.getDocumentElement();
			String[] name = foldername.split("\\\\");
			 String dir = getDeep2(foldername);
			 String []dirs=  dir.split("/");
			 String path = "/rootdir";
			 for(int i=0;i<dirs.length;i++){
				 path+="/" +dirs[i];
			 }
			Element node = (Element) selectSingleNode(path , root);
			
			
			//System.out.println(" ************" +name[name.length - 1] +"*********");
			if (node != null) {
				
				node.getParentNode().removeChild(node);
				int id=  Integer.parseInt(root.getAttribute("version"));
				root.setAttribute("version", String.valueOf(id+1));
				
			}
			TransformerFactory transFactory = TransformerFactory.newInstance();
			try {
				Transformer transformer = transFactory.newTransformer();
				transformer.setOutputProperty("encoding", "utf-8");
				transformer.setOutputProperty("indent", "yes");
				DOMSource source = new DOMSource();
				source.setNode(xmldoc);
				StreamResult result = new StreamResult();
				try {
					result.setOutputStream(new FileOutputStream(filename));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				transformer.transform(source, result);
			} catch (TransformerConfigurationException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	


	public void setdir(String filename, String foldername) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			factory.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = factory.newDocumentBuilder();
			Document xmldoc = db.parse(new File(filename));
			Element root = xmldoc.getDocumentElement();
			String[] name = foldername.split("\\\\");
			 String dir = getDeep2(foldername);
			 String []dirs=  dir.split("/");
			 String path = "/rootdir";
			 for(int i=0;i<dirs.length-1;i++){
				 path+="/" +dirs[i];
			 }
				
			Element node = (Element) selectSingleNode(path , root);
			if (node != null) {
				int temp = Integer.parseInt(node.getAttribute("id")) + 1;
				node.setAttribute("id", String.valueOf(temp));
				node.setAttribute("name", name[name.length - 1]);
				int id=  Integer.parseInt(root.getAttribute("version"));
				root.setAttribute("version", String.valueOf(id+1));
			}
			TransformerFactory transFactory = TransformerFactory.newInstance();
			try {
				Transformer transformer = transFactory.newTransformer();
				transformer.setOutputProperty("encoding", "utf-8");
				transformer.setOutputProperty("indent", "yes");
				DOMSource source = new DOMSource();
				source.setNode(xmldoc);
				StreamResult result = new StreamResult();
				try {
					result.setOutputStream(new FileOutputStream(filename));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				transformer.transform(source, result);
			} catch (TransformerConfigurationException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	

	//文件
	public void updFile(String filename, String foldername, String file) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			factory.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = factory.newDocumentBuilder();
			Document xmldoc = db.parse(new File(filename));
			Element root = xmldoc.getDocumentElement();
			String[] name = foldername.split("\\\\");

			 String dir = getDeep2(foldername);
			String path = "/rootdir"+dir;

			Element node = (Element) selectSingleNode(path, root);
			String dirname= ((Element)node.getParentNode()).getAttribute("name");
			 
			if (node != null) {
				if(dirname.equals(name[name.length - 2])){
				Element child = xmldoc.createElement("file");
				child.setAttribute("name", file);
				child.setAttribute("id", "1");
				child.setAttribute("sortid", "0");
				node.appendChild(child);
				int id=  Integer.parseInt(root.getAttribute("version"));
				root.setAttribute("version", String.valueOf(id+1));}
			}
			TransformerFactory transFactory = TransformerFactory.newInstance();
			try {
				Transformer transformer = transFactory.newTransformer();
				transformer.setOutputProperty("encoding", "utf-8");
				transformer.setOutputProperty("indent", "yes");
				DOMSource source = new DOMSource();
				source.setNode(xmldoc);
				StreamResult result = new StreamResult();
				try {
					result.setOutputStream(new FileOutputStream(filename));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				transformer.transform(source, result);
			} catch (TransformerConfigurationException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

	public void delFile(String filename, String foldername, String file) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			factory.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = factory.newDocumentBuilder();
			Document xmldoc = db.parse(new File(filename));
			Element root = xmldoc.getDocumentElement();
			// String[] name=foldername.split("\\\\");
			String[] myfile = file.split("\\\\");
			String dir = getDeep2(foldername);
			String path = "/rootdir"+dir;
			//String path = "/rootdir";
//			for (int i = 0; i < deep; i++) {
//				path += "/dir";
//			}
			path += "/file";
			Element node = (Element) selectSingleNode(path + "[@name='"
					+ myfile[myfile.length - 1] + "']", root);
			
			if (node != null) {
				node.getParentNode().removeChild(node);
				int id=  Integer.parseInt(root.getAttribute("version"));
				root.setAttribute("version", String.valueOf(id+1));
			}
			TransformerFactory transFactory = TransformerFactory.newInstance();
			try {
				Transformer transformer = transFactory.newTransformer();
				transformer.setOutputProperty("encoding", "utf-8");
				transformer.setOutputProperty("indent", "yes");
				DOMSource source = new DOMSource();
				source.setNode(xmldoc);
				StreamResult result = new StreamResult();
				try {
					result.setOutputStream(new FileOutputStream(filename));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				transformer.transform(source, result);
			} catch (TransformerConfigurationException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	
	
	public void renFile(String filename, String foldername, String file,
			String newFile) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			factory.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = factory.newDocumentBuilder();
			Document xmldoc = db.parse(new File(filename));
			Element root = xmldoc.getDocumentElement();
			// String[] myfile=file.split("\\\\");
//			int deep = Integer.parseInt(getDeep(foldername));
//			String path = "/rootdir";
//			for (int i = 0; i < deep; i++) {
//				path += "/dir";
//			}
			String dir = getDeep2(foldername);
			String path = "/rootdir"+dir;
			path += "/file";
			Element node = (Element) selectSingleNode(path + "[@name='" + file
					+ "']", root);
			if (node != null) {
				int temp = Integer.parseInt(node.getAttribute("id")) + 1;
				node.setAttribute("id", String.valueOf(temp));
				node.setAttribute("name", newFile);
				int id=  Integer.parseInt(root.getAttribute("version"));
				root.setAttribute("version", String.valueOf(id+1));
			}

			TransformerFactory transFactory = TransformerFactory.newInstance();
			try {
				Transformer transformer = transFactory.newTransformer();
				transformer.setOutputProperty("encoding", "utf-8");
				transformer.setOutputProperty("indent", "yes");
				DOMSource source = new DOMSource();
				source.setNode(xmldoc);
				StreamResult result = new StreamResult();
				try {
					result.setOutputStream(new FileOutputStream(filename));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				transformer.transform(source, result);
			} catch (TransformerConfigurationException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//设置序号
	public void setNode(String  filename ,String nodetext, String order) {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			factory.setIgnoringElementContentWhitespace(true);
			DocumentBuilder db = factory.newDocumentBuilder();
			Document xmldoc = db.parse(new File(filename));
			Element root = xmldoc.getDocumentElement();
			// String[] name=foldername.split("\\\\");
			String[] myfile = nodetext.split("\\\\");
			String dir = getDeep2(nodetext);
			String path = "/rootdir"+dir;
			File file= new File(nodetext);
			if(!file.isDirectory()){path= path.substring(0, path.lastIndexOf("/"));
		    path += "/file[@name='"
					+ myfile[myfile.length - 1] + "']"; }
//			if(myfile[myfile.length - 1].indexOf(".")!=-1){
//			path= path.substring(0, path.length()-4);
//			 path += "/file";}
			Element node = (Element) selectSingleNode(path , root);
			if (node != null) {
				node.setAttribute("sortid", order);
				int id=  Integer.parseInt(root.getAttribute("version"));
				root.setAttribute("version", String.valueOf(id+1));
			}
			TransformerFactory transFactory = TransformerFactory.newInstance();
			try {
				Transformer transformer = transFactory.newTransformer();
				transformer.setOutputProperty("encoding", "utf-8");
				transformer.setOutputProperty("indent", "yes");
				DOMSource source = new DOMSource();
				source.setNode(xmldoc);
				StreamResult result = new StreamResult();
				try {
					result.setOutputStream(new FileOutputStream(filename));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				transformer.transform(source, result);
			} catch (TransformerConfigurationException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		

	}

	public int getOrder(String nodetext) {
		String[] myfile = nodetext.split("\\\\");
		int deep = Integer.parseInt(getDeep(nodetext));
		String path = "/rootdir";
		for (int i = 0; i < deep; i++) {
			path += "/dir";
		}
		if(myfile[myfile.length - 1].indexOf(".")!=-1){
		 path += "/file";}
		Element node = (Element) selectSingleNode(path + "[@name='"
				+ myfile[myfile.length - 1] + "']", root);
		if (node != null) {
			return Integer.parseInt(node.getAttribute("sortid"));
		} else {
			return 9999999;
		}
	}

	public String getDeep2(String path) {
		String[] deep = null;
		if (path != null && path.length() != 0) {
			path = path.replace(base + "\\", "");
		}
		deep = path.split("\\\\");
		String dir="";
		if (deep != null){
			for (int i = 0; i < deep.length; i++) {
				dir += "/dir"
					+"[@name='"
					+ deep[i] + "']";
			}
			}else{
				dir="/dir";
			}	
		return dir;
	}

	public String getDeep(String path) {
		        String deep[] = (String[])null;
		       if (path != null && path.length() != 0) {
		            path = path.replace((new StringBuilder(String.valueOf(base))).append("\\").toString(), "");
		                }
		        deep = path.split("\\\\");
		        if (deep != null) {
		            return (new StringBuilder()).append(deep.length).toString();
		                } else {
		            return "1";
		                }
		            }
	
	public String getFileName(String path) {
		String fileName = " ";
		if (path != null && path.length() != 0) {
			fileName = path.substring(path.lastIndexOf("\\") + 1);
		}
		return fileName;
	}

	public static Node selectSingleNode(String express, Object source) {// 查找节点,并返回第一个符合条件节点
		Node result = null;
		XPathFactory xpathFactory = XPathFactory.newInstance();
		XPath xpath = xpathFactory.newXPath();
		try {
			result = (Node) xpath
					.evaluate(express, source, XPathConstants.NODE);
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}

		return result;
	}

	public void output() {// 将node的XML字符串输出到控制台
		TransformerFactory transFactory = TransformerFactory.newInstance();
		try {
			Transformer transformer = transFactory.newTransformer();
			transformer.setOutputProperty("encoding", "utf-8");
			transformer.setOutputProperty("indent", "yes");
			DOMSource source = new DOMSource();
			source.setNode(xmldoc);
			StreamResult result = new StreamResult();
			try {
				result.setOutputStream(new FileOutputStream(filename));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			transformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

}

你可能感兴趣的:(java,xml)