java xml 的增、刪、改、查

package richinfo.uec.dao;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;

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 javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

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

import richinfo.uec.common.XmlReader;
import richinfo.uec.uecAdmin.Bean.CommonProblem;

@Service("CommonProblemDao")
public class CommonProblemDao {
	private static Logger log = Logger.getLogger(CommonProblemDao.class);
	private static DocumentBuilderFactory factory = DocumentBuilderFactory
			.newInstance();
	private static final String FILENAME = "commonProblem.xml";
	private static URL urlFile = null;
	static {
		urlFile = XmlReader.class.getClassLoader().getResource(FILENAME);
	}
	/**
	 * 將Document輸出到文件
	 * @param fileName
	 * @param doc
	 */
	 public static void saveXml(String fileName, Document doc) {
	        TransformerFactory transFactory=TransformerFactory.newInstance();
	        try {
	            Transformer transformer = transFactory.newTransformer();
	            transformer.setOutputProperty("encoding", "utf-8");
	            transformer.setOutputProperty("indent", "yes");
	            DOMSource source=new DOMSource();
	            source.setNode(doc);
	            StreamResult result=new StreamResult();
	            result.setOutputStream(new FileOutputStream(fileName));
	            transformer.transform(source, result);
	        } catch (Exception e) {
	            e.printStackTrace();
	        } 
	    }
	 	/**
		 * 將node的XML字符串輸出到控制檯
		 * @param node
		 */
		 public static void output(Node node) {
		        TransformerFactory transFactory=TransformerFactory.newInstance();
		        try {
		            Transformer transformer = transFactory.newTransformer();
		            transformer.setOutputProperty("encoding", "utf-8");
		            transformer.setOutputProperty("indent", "yes");
		            DOMSource source=new DOMSource();
		            source.setNode(node);
		            StreamResult result=new StreamResult();
		            result.setOutputStream(System.out);
		            
		            transformer.transform(source, result);
		        } catch (Exception e) {
		        	log.error(e);
		            e.printStackTrace();
		        }
		    }
	/**
	 * 查找節點,返回符合條件的節點集。
	 * @param express
	 * @param source
	 * @return
	 */
	 public static NodeList selectNodes(String express, Object source) {
	        NodeList result=null;
	        XPathFactory xpathFactory=XPathFactory.newInstance();
	        XPath xpath=xpathFactory.newXPath();
	        try {
	            result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
	        } catch (XPathExpressionException e) {
	        	log.error(e);
	            e.printStackTrace();
	        }
	        
	        return result;
	    }
	
	/**
	 * 查找節點,並返回第一個符合條件節點
	 * @param express
	 * @param source
	 * @return
	 */
	 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) {
	        	log.error(e);
	            e.printStackTrace();
	        }
	        
	        return result;
	    }
	 /**
	  * 新增一個問題
	  * @param problem
	  * @return
	  */
	 public static boolean createNode(CommonProblem problem){
		 Element theProblem=null, theElem=null, root=null;
		 boolean flag = false ;
		 try {
			 Document xmldoc = getDocument(); //獲得一個document
			 root = xmldoc.getDocumentElement(); //取得根節點
			 theProblem = xmldoc.createElement("Problem");
	         theElem=xmldoc.createElement("Id");
	         theElem.setTextContent(getMaxId()+"");
	         theProblem.appendChild(theElem);
	         theElem=xmldoc.createElement("Name");
	         theElem.setTextContent(problem.getName());
	         theProblem.appendChild(theElem);
	         theElem=xmldoc.createElement("Url");
	         theElem.setTextContent(problem.getUrl());
	         theProblem.appendChild(theElem);
	         root.appendChild(theProblem);
	         //TODO
	         //output(xmldoc);
	         saveXml(urlFile.getPath(), xmldoc);
	         flag = true;
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		
		 return flag;
	 }
	 /**
	  * 修改
	  * @param problem
	  * @return
	  */
	 public static boolean upNode(CommonProblem problem){
		 Element theProblem=null, root=null;
		 boolean flag = false ;
		 try {
			 Document xmldoc = getDocument(); //獲得一個document
			 root = xmldoc.getDocumentElement(); //取得根節點
			 theProblem = (Element) selectSingleNode("/Problems/Problem[Id='"+problem.getId()+"']", root);
			if(problem.getName()!=null){
				 //getElementsByTagName 返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當於xpath 的".//price"。
				 theProblem.getElementsByTagName("Name").item(0).setTextContent(problem.getName());
			}
			if(problem.getUrl()!=null){
				 //getElementsByTagName 返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當於xpath 的".//price"。
				 theProblem.getElementsByTagName("Url").item(0).setTextContent(problem.getUrl());
			}
			  //TODO
	         //output(xmldoc);
	         saveXml(urlFile.getPath(), xmldoc);
			 flag =true ;
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return flag ;
	 }
	 /**
	  * 
	  * @param id
	  * @return
	  */
	 public static boolean delNode(int id){
		 Element theProblem=null, root=null;
		 boolean flag = false ;
		 try {
			 Document xmldoc = getDocument(); //獲得一個document
			 root = xmldoc.getDocumentElement(); //取得根節點
			 theProblem = (Element) selectSingleNode("/Problems/Problem[Id='"+id+"']", root);
			 theProblem.getParentNode().removeChild(theProblem);
			  //TODO
	        //output(xmldoc);
	         saveXml(urlFile.getPath(), xmldoc);
			 flag =true ;
		 } catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return flag ;
	 }
	 public static int getMaxId(){
		 Element root=null;
		 int id = 0 ;
		 try {
			 Document xmldoc = getDocument(); //獲得一個document
			 root = xmldoc.getDocumentElement(); //取得根節點
			 NodeList problems=selectNodes("/Problems/Problem/Id", root);
			 int[] ids = new int[problems.getLength()];
			 for(int i=0;i<problems.getLength();i++) {
				  String value = problems.item(i).getTextContent();
				  ids[i] = Integer.parseInt(value);
	        }
			int temp;
			if(ids.length>0){
			for (int i = 0; i < ids.length; i++) {
				for (int j = i+1; j < ids.length; j++) {
					if(ids[i]<ids[j]){
						temp = ids[i];
						ids[i] = ids[j];
						ids[j] = temp;
					}
				}
			}
			id = ids[0]+1;
			}else{
				id=1 ;
			}
			
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
		}
		return id ;
	 }
	/**
	 * 獲取xml Document
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Document getDocument() throws Exception {
		Document xmldoc = null;
		factory.setIgnoringElementContentWhitespace(true);
		DocumentBuilder db = factory.newDocumentBuilder();
		if (urlFile != null)
			xmldoc = db.parse(new File(urlFile.toURI()));
		return xmldoc;
	}
//	public static void main(String[] args) {
//		//int id = getMaxId();
//		CommonProblem problem = new CommonProblem();
//		//problem.setId(1);
//		problem.setName("a");
//		problem.setUrl("url");
//		boolean flag = false ;
//		//flag = createNode(problem);
//		//flag = upNode(problem);
//		flag = delNode(11);
//		System.out.println(flag);
//	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章