zoukankan      html  css  js  c++  java
  • Dom4j读取xml

    使用很简单,所以直接上代码

    依赖:

      <!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
    	<dependency>
    	    <groupId>dom4j</groupId>
    	    <artifactId>dom4j</artifactId>
    	    <version>1.6.1</version>
    	</dependency>

    工具类:

    package com.xx.dao;
    
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.util.List;
    
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.SAXReader;
    import org.dom4j.io.XMLWriter;
    
    import com.xx.controller.Hello;
    /*
     *xml读取写入工具类 
     */
    public class XmlReadWriteUtil {
    	//创建或获取文件对象
    	//public static String filePath=null;
    	public static File file = null;
    	static {
    		String path=getPath();
    		file = new File(path);
         	if(!file.exists()){
         		try {
     				file.createNewFile();
     		     	PrintWriter out = new PrintWriter(new BufferedWriter(
     		                new FileWriter(file, true)));
     		     	out.println("<?xml version="1.0" encoding="UTF-8"?>"); 
     		     	out.println("<users>");
     		     	out.println("</users>");
     		     	if (out != null) {
     		            out.close();
     		        }
     				
     			} catch (IOException e) {
     				e.printStackTrace();
     			}
         	}
         	
    	}
    	public static String getPath() {
    		String project_root=XmlReadWriteUtil.class.getResource("/").toString().replace("file:/", ""); 
    		project_root = project_root.substring(0,project_root.indexOf("/WEB-INF"))+"/user.xml"; 
    		System.out.println(project_root);
    		return project_root;
    	}
    	
    	
    	
    	/**
    	 * 获取根节点
    	 * @return
    	 * @throws Exception
    	 */
    	public static Document getDocument() throws Exception {  
    
            // 创建saxReader对象  
            SAXReader reader = new SAXReader();  
            // 通过read方法读取一个文件 转换成Document对象  
            Document document = reader.read(file);  
            
            return document ;
        }
    	/**
    	 * 读取数据
    	 * @throws Exception
    	 */
    	public static void readXML() throws Exception {  
    
            
    		Document document = getDocument();
          //获取根节点元素对象  
            Element root = document.getRootElement();  
            //获取根元素下所有节点
    	    List<org.dom4j.Element> list = root.elements();
    	    for(org.dom4j.Element e:list){
    	       //获取属性值
    	        String no   = e.attributeValue("no");
    	        String name = e.element("name").getText();
    	        String age  = e.element("age").getText();
    	        System.out.println(no+name+age);
    	    }
    
        } 
    	 
    	public static void createNewNode(){
    		
    		 Document document;
    		try {
    			document = getDocument();
    			 Element root = document.getRootElement();  
    	         Element supercarElement= root.addElement("user").addAttribute("id", "2019");;
    	         Element name = supercarElement.addElement("name");
    	         name.addText("jack");
    	         Element age= supercarElement.addElement("age");
    	         age.addText("18");
    	         writer(document);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
             
    	}
    	  /** 
         * 把document对象写入新的文件 
         *  
         * @param document 
         * @throws Exception 
         */  
        public static void writer(Document document) throws Exception {  
            // 紧凑的格式  
            // OutputFormat format = OutputFormat.createCompactFormat();  
            // 排版缩进的格式  
            OutputFormat format = OutputFormat.createPrettyPrint();  
            // 设置编码  
            //format.setEncoding("UTF-8");  
            // 创建XMLWriter对象,指定了写出文件及编码格式  
            // XMLWriter writer = new XMLWriter(new FileWriter(new  
            // File("src//a.xml")),format);  
            XMLWriter writer = new XMLWriter(new OutputStreamWriter(  
                    new FileOutputStream(file), "UTF-8"), format);  
            // 写入  
            writer.write(document);  
            // 立即写入  
            writer.flush();  
            // 关闭操作  
            writer.close();  
        }  
    	
    	
    	
    	
    }
    
     
     
  • 相关阅读:
    djongo 前端页面展示自定义api返回的列表数据,并拼接到table上
    ou are trying to add a non-nullable field 'address' to person without a default; we can't do that (the database needs something to populate existing rows).
    python string 类型的公钥转换类型并解密
    Django 禁止访问403,CSRF验证失败,相应中断
    springboot async
    此博客可能不再更新,往后博文将发布在 GitHub 中
    css 中 transition 需要注意的问题
    学习笔记(九)
    微信小程序 drawImage 问题
    学习笔记(八)
  • 原文地址:https://www.cnblogs.com/the-fool/p/11054158.html
Copyright © 2011-2022 走看看