• Java之Dom4j(RCUDS)


    package anby.com;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    
    import org.dom4j.Attribute;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.io.SAXReader;
    import org.dom4j.io.SAXWriter;
    import org.dom4j.io.XMLWriter;
    import org.xml.sax.SAXException;
    
    public class Dom4jCUD {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args)throws Exception {
    		
    		Document doc= readXml("Book.xml");
    		//使用 Xpath进行查询
    		Node node= doc.selectSingleNode("//book[@id='boo1']");
    		Element ele=(Element)node;
    		//获取元素内容
    		Element  titileEle=ele.element("titile");
    		System.out.println(ele.elementText("titile"));
    		
    		//修改元素内容
    		titileEle.setText("孔乙己");
    		System.out.println(ele.elementText("titile"));
    		
    		//删除元素
    		Node bookNode=doc.selectSingleNode("//book[@id='boo2']");
    		Element Parent=bookNode.getParent();//获取父节点
    	   Parent.remove(bookNode);
    	   
    		//创建元素
    		 Element root=doc.getRootElement();
    		 Element newbook=DocumentHelper.createElement("book");
    		 Attribute subTiltle= DocumentHelper.createAttribute(newbook, "id", "boo3");
    		 newbook.addAttribute("id", "boo3");//增加属性
    		 //创建子元素
    		 Element subTiltle1= DocumentHelper.createElement("titile");
    		subTiltle1.setText("孔乙己");
    		 newbook.add(subTiltle1);    //父元素增加子元素
    
    		 Element subPrice= DocumentHelper.createElement("price");
    		 subPrice.setText("30");
    		newbook.add(subPrice);    //父元素增加子元素
    			 
    
    		root.add(newbook);//父节点增加book、节点
    		
    		//格式不规范,需要格式化xml,还有出现中文乱码现象
    		 saveXml(doc);
    	}
    	
    	public static Document readXml(String path) throws DocumentException
    	{
          SAXReader saxreader =new SAXReader();
          return saxreader.read(new File(path));
    	}
    	
      public static void saveXml(Document document) throws SAXException, IOException
      {
    	  XMLWriter writer=new XMLWriter(new FileWriter("Books.xml"));
    	  writer.write(document);
    	  writer.close();
      }
    	
    }
    

      

  • 相关阅读:
    Binder机制,从Java到C (大纲)
    大陆台湾计算机术语比对
    关于nginx架构探究(2)
    关于nginx架构探究(1)
    关于开源中文搜索引擎架构coreseek中算法详解
    关于linux定时操作cron的理解
    sqlachemy 使用实例
    nginx+uwsgi+flask搭建python-web应用程序
    VC维
    关于zMPLS的设计解析
  • 原文地址:https://www.cnblogs.com/anbylau2130/p/3019296.html
Copyright © 2020-2023  润新知