【无标题】对xml文件进行增删查改

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.map.HashedMap;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class XmlUtil {
	private static  Logger logger = LoggerFactory.getLogger(XmlUtil.class);
	//修改
	 static void updateXMLByDOM(String fileName,String time) throws Exception { 
	            // 2.通过reader对象的read方法加载xml文件,获取Document对象
	            Document document = getDocument();
	            Element eledoc = document.getRootElement();// 通过document对象获取根节点
	            
	            @SuppressWarnings("unchecked")
				List<Element> eles = eledoc.elements();
	            for (Element ele : eles) 
	            {
	            	if(ele.attribute("id").getValue() .equals(fileName)) {
	            		logger.info("修改xml文件名为"+fileName+"時間time為"+time);
	            		ele.element("time").setText(time);
	            	}
	            }
	            writeToNewXMLDocument(document);
	      
	        
	 }
	 //新增
	 public static void AddXMLByDOM(String fileName,String time) throws Exception{ 
		 
		 Document document = getDocument();
		 Element root = document.getRootElement();
		 Element newfile = root.addElement("file");
		 newfile.addAttribute("id", fileName);
		 Element title = newfile.addElement("time");
		 title.setText(time);
		 writeToNewXMLDocument(document);
	 }
	 //刪除該節點
	 @SuppressWarnings("rawtypes")
	public static void DeleteXMLByDOM(String fileName) throws Exception{ 
		 Document document = getDocument();
		 Element eledoc = document.getRootElement();// 通过document对象获取根节点
		 for (Iterator it =  eledoc.elementIterator(); it.hasNext();) {
		      Element ele = (Element) it.next();
		      String id = ele.attributeValue("id");
		      if (fileName.equals(id)) {
		        Element parent = ele.getParent();
		        parent.remove(ele);
		        logger.info("删除xml文件名为"+fileName+"的数据");
		      }
		 }
		 writeToNewXMLDocument(document);
	 }
	 
	 //查詢是否有
	 @SuppressWarnings("rawtypes")
	public static  Map<String,Object> selectXMLByDOM(String fileName) throws Exception{ 
		 Document document = getDocument();
		 Map<String,Object> map=new HashedMap<>();
		 Element eledoc = document.getRootElement();// 通过document对象获取根节点
		 for (Iterator it =  eledoc.elementIterator(); it.hasNext();) {
		      Element ele = (Element) it.next();
		      String id = ele.attributeValue("id");
		      if (fileName.equals(id)) {
		    	  map.put("time", ele.element("time").getText());
		    	  map.put("result", true);
		        return map;
		      }
		 }
		 map.put("result", false);
		 return  map;
	 }
	 
	 
	 /**
	   * 该方法用于得到document对象。
	   * 
	   * @return
	   * @throws Exception
	   */
	  private static Document getDocument() throws Exception {
	    SAXReader sr = new SAXReader();
	    Document document = sr.read(new File("xml/products.xml"));
	    return document;
	  }
	  /**
	   * 通过document对象将内存中的dom树保存到新的xml文档。
	   * 
	   * @param document
	   * @throws Exception
	   */
	  private static void writeToNewXMLDocument(Document document)
	      throws Exception {
		  OutputFormat format=OutputFormat.createPrettyPrint();
          format.setEncoding("UTF-8");
          org.dom4j.io.XMLWriter writer=new org.dom4j.io.XMLWriter(new FileOutputStream(new File("xml/products.xml")), format);
          writer.write(document);
          writer.close();
	  }
	 public static void main(String[] args) {
		 try {
		     updateXMLByDOM("2021.12.12.csv","110:99");
			 //AddXMLByDOM("2021.12.17.csv","55:22");
		     //DeleteXMLByDOM("2021.12.17.csv","55:22");
		     //System.out.println(selectXMLByDOM("LH_B5_T6_cijijiance_21.12.06.csv"));
		}catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值