美文网首页
Dom4j的使用

Dom4j的使用

作者: A_一只小菜鸟 | 来源:发表于2020-08-17 17:25 被阅读0次

    dom4j是一个Java的XML API,是jdom的升级品,用来读写XML文件的。dom4j是一个十分优秀的javaXML API,具有性能优异、功能强大和极其易使用的特点,它的性能超过sun公司官方的dom技术,同时它也是一个开放源代码的软件,可以在SourceForge上找到它。

    一、dom4j介绍

    使用方式:在pom.xml中导入dom4j对应的jar

    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency>
    

    优点:dom4j使Java生成和解析XML灵活性变高,并且代码易于维护。

    API操作类:
    Document:表示xml文档信息,是一个树形结构
    Eelment:表示xml的元素结点,提供一些操作其子元素方法的,如文本、属性、名称空间等
    Attribute:表示元素结点中的属性

    二、常用API

    1.创建Document 和Element对象:

    Document doc=DocumentHelper.createDocument();
    Element eltRoot=DocumentHelper.createElement("student");
    doc.setRootElement(eltRoot);
    

    2.或者先准备好根元素,使用有参数的构造方法创建Document对象。

    Element eltRoot=DocumentHelper.createElement(“student”);
    Document doc=DocumentHelper.createDocument(eltRoot);
    

    3.添加节点和设置节点内容

    Element eltName=eltRoot.addElement(“name”);
    Element eltAge=eltRoot.addElement(“age”);
    eltName.setText(“张三”);
    eltAge.setText(“18”);
    

    4.添加属性

    eltRoot.addAttribute(“sn”,”01”);
    

    5.使用 SAXReader 构建dom4j文档对象

    SAXReader saxReader=new SAXReader();
    File file=new File(“student.xml”);
    Document doc=saxReader.read(file);
    

    6.使用DOMReader 构建dom4j 文档对象

    DocumentBuilderFactory dbf=new DocumentBuilderFactory.newInstance();
    DocumentBuilder db=dbf.newDocumentBuilder();
    File file=new File(“student.xml”);
    org.w3c.dom.Document document=db.parse(file);
    DOMReader domReader=new DOMReader();
    org.dom4j.Document doc=domReader.read(document);
    

    7.访问根节点:

    Element root=doc.getRootElement();
    

    8.访问所有节点:

    java.util.List childrenList=elt.elements();
    

    9.访问指定名称的所有节点

    java.util.Liat childrenList=elt.elements(“student”);
    

    10.访问指定名称第一个节点

    Element eltChild=elt.element(“student”);
    

    11.要迭代某个元素的所有子元素

    for(java.util.Iterator it=root.elementIterator();it.hasNext()){
    Element element =it.hasNext();
    ……
    }
    

    输出文档:
    对象:XMLWriter 实例方法:write(Document doc)
    常用的几种构造方法总结:
    1:无参数:
    2:字节流参数
    3:字符流参数。
    4:文档输出格式类参数。
    示例代码1:
    输出文档内容到控制台

    XMLWriter xw=new XMLWriter();
    xw.write(doc);
    

    三、dom4j 生成 xml

    实现步骤:

    第一步:创建一个Document实例
    Document doc = DocumentHelper.createDocument();

    第二步:先添加一个根结点,然后再添加子结点,构造成一个树形结构
    Element root = doc.addElement("root");

    第三步:添加xml文件样式(也可自定义样式),并输出xml文件到指定的路径下
    OutputFormat format = OutputFormat.createPrettyPrint();
    XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
    writer.write(doc);
    实现源码

    package com.oysept.xml;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.XMLWriter;
    import org.jdom2.output.Format;
    
    /**
     * dom4j生成xml
     * @author ouyangjun
     */
    
    public class CreateDom4j {
    
        public static void main(String[] args) {
            // 执行dom4j生成xml方法
            createDom4j(new File("E:\\dom4j.xml"));
        }
    
        public static void createDom4j(File file) {
            try {
                // 创建一个Document实例
                Document doc = DocumentHelper.createDocument();
                // 添加根节点
                Element root = doc.addElement("root");
                // 在根节点下添加第一个子节点
                Element oneChildElement= root.addElement("person").addAttribute("attr", "root noe");
    
                oneChildElement.addElement("people").addAttribute("attr", "child one").addText("person one child one");
    
                oneChildElement.addElement("people") .addAttribute("attr", "child two") .addText("person one child two");
    
                // 在根节点下添加第一个子节点
    
                Element twoChildElement= root.addElement("person").addAttribute("attr", "root two");
    
                twoChildElement.addElement("people") .addAttribute("attr", "child one").addText("person two child one");
                twoChildElement.addElement("people") .addAttribute("attr", "child two").addText("person two child two");
    
                // xml格式化样式
                // OutputFormat format = OutputFormat.createPrettyPrint(); // 默认样式
    
                // 自定义xml样式
                OutputFormat format = new OutputFormat();
                format.setIndentSize(2);  // 行缩进
                format.setNewlines(true); // 一个结点为一行
                format.setTrimText(true); // 去重空格
                format.setPadText(true);
                format.setNewLineAfterDeclaration(false); // 放置xml文件中第二行为空白行
    
                // 输出xml文件
                XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
                writer.write(doc);
                System.out.println("dom4j CreateDom4j success!");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    XML文件效果图:


    untitled.png

    四、dom4j解析xml

    实现步骤

    第一步:创建一个SAXReader解析器
    SAXReader reader = new SAXReader();

    第二步:解析xml文件,重新构建成一个Document对象
    Document doc = reader.read(file);

    第三步:处理Document对象信息,在控制台打印

    实现源码:

    package com.oysept.xml; 
    
    import java.io.File;
    import java.util.Iterator;
    import java.util.List;
    import org.dom4j.Attribute;
    import org.dom4j.CDATA;
    import org.dom4j.Comment;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.Text;
    import org.dom4j.io.SAXReader;
    
    /**
     * dom4j解析xml
     * @author ouyangjun
     */
    
    public class ParseDom4j {
    
        public static void main(String[] args) {
            // 执行dom4j解析xml方法
            parseDom4j(new File("E:\\dom4j.xml"));
        }
    
        public static void parseDom4j(File file) {
            try {
                // 创建一个SAXReader解析器
                SAXReader reader = new SAXReader();
                // 读取xml文件,转换成Document结点
                Document doc = reader.read(file);
                // 递归打印xml文档信息
                StringBuffer buffer = new StringBuffer();
                parseElement(doc.getRootElement(), buffer);
                System.out.println(buffer.toString());
            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
    
        @SuppressWarnings("unchecked")
        public static void parseElement(Element element, StringBuffer buffer) {
            buffer.append("<"+element.getName());
            List<Attribute> attrs = element.attributes();
            if (attrs != null) {
                for (Attribute attr : attrs) {
                    buffer.append(" "+attr.getName()+"=\""+attr.getValue()+"\"");
                }
            }
            buffer.append(">");
            Iterator<Node> iterator = element.nodeIterator();
            while (iterator.hasNext()) {
                Node node = iterator.next();
                if (node instanceof Element) {
                    Element eleNode = (Element) node;
                    parseElement(eleNode, buffer);
                }
                if (node instanceof Text) {
                    Text text = (Text) node;
                    buffer.append(text.getText());
                }
    
                if (node instanceof CDATA) {
                    CDATA dataNode = (CDATA) node;
                    buffer.append(dataNode.getText());
                }
    
                if (node instanceof Comment) {
                    Comment comNode = (Comment) node;
                    buffer.append(comNode.getText());
                }
            }
            buffer.append("</"+element.getName()+">");
        }
    }
    

    XML文件解析效果图打印:


    untitled.png

    五、dom4j解析生成字符串

    import java.io.IOException;
    import java.io.StringWriter;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.XMLWriter;
    
    /**
     *
     * @author y
     */
    public class Test {
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) throws DocumentException {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("name", "李四");
            map.put("age", 25);
            
            //System.out.println(map2xml(map));
            
            
            List<Object> list = new ArrayList<Object>();
            list.add("测试1");
            list.add("测试2");
            list.add("测试3");
            
            //System.out.println(list2xml(list,"items"));
            
            List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
            Map<String,Object> map1 = new HashMap<String,Object>();
            map1.put("name", "张三");
            map1.put("age", 23);
            listMap.add(map1);
            map1 = new HashMap<String,Object>();
            map1.put("name", "李四");
            map1.put("age", 24);
            listMap.add(map1);
            map1 = new HashMap<String,Object>();
            map1.put("name", "王五");
            map1.put("age", 25);
            listMap.add(map1);
            
            System.out.println(listMap2xml(listMap,"users","user"));
            
        }
        
        
        public static String listMap2xml(List<Map<String,Object>> list,String listRoot,String mapRoot){
            Document doc = DocumentHelper.createDocument();
            
            Element rootEle = doc.addElement("result");
            Element noEle = rootEle.addElement("no");
            Element msgEle = rootEle.addElement("msg");
            
            if(null!=list && !list.isEmpty()){
                noEle.setText("1");
                msgEle.setText("成功获取相关信息");
                
                Element listRootEle = rootEle.addElement(listRoot);
                
                for(Map<String,Object> map:list){
                    
                    Element mapRootELe = listRootEle.addElement(mapRoot);
                    
                    Set<Map.Entry<String,Object>> set = map.entrySet();
                    Iterator<Map.Entry<String,Object>> iter = set.iterator();
                    while(iter.hasNext()){
                        Map.Entry<String,Object> entry = (Map.Entry<String,Object>)iter.next();
                        
                        Element ele = mapRootELe.addElement(entry.getKey());
                        ele.setText(String.valueOf(entry.getValue()));
                    }
                }
            }else{
                noEle.setText("0");
                msgEle.setText("没有获取到相关信息");
            }
            
            StringWriter sw = new StringWriter();
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            
            try {
                
                XMLWriter xmlWriter = new XMLWriter(sw, format);
                
                xmlWriter.write(doc);
            } catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                try {
                    sw.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    
            return sw.toString();
        }
    
        
        public static String list2xml(List<Object> list,String itemRoot){
            Document doc = DocumentHelper.createDocument();
            
            Element rootEle = doc.addElement("result");
            Element noEle = rootEle.addElement("no");
            Element msgEle = rootEle.addElement("msg");
            
            if(null!=list && !list.isEmpty()){
                noEle.setText("1");
                msgEle.setText("成功获取相关信息");
                
                Element itemRootEle = rootEle.addElement(itemRoot);
                
                for(Object obj:list){
                    Element ele = itemRootEle.addElement("item");
                    ele.setText(String.valueOf(obj));
                }
            }else{
                noEle.setText("0");
                msgEle.setText("没有获取到相关信息");
            }
            
            StringWriter sw = new StringWriter();
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            
            try {
                
                XMLWriter xmlWriter = new XMLWriter(sw, format);
                
                xmlWriter.write(doc);
            } catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                try {
                    sw.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    
            return sw.toString();
        }
        
        public static String map2xml(Map<String, Object> map) {
            Document doc = DocumentHelper.createDocument();
            
            Element rootEle = doc.addElement("result");
            
            Element noEle = rootEle.addElement("no");
            Element msgEle = rootEle.addElement("msg");
            
            if(null!=map && !map.isEmpty()){
                noEle.setText("1");
                msgEle.setText("成功获取相关信息");
                
                Set<Map.Entry<String, Object>> set = map.entrySet();
                Iterator<Map.Entry<String, Object>> iter = set.iterator();
                while(iter.hasNext()){
                    Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iter.next();
                    
                    Element ele = rootEle.addElement(entry.getKey());
                    ele.setText(String.valueOf(entry.getValue()));
                }
            }else{
                noEle.setText("0");
                msgEle.setText("没有获取到相关信息");
            }
            
            StringWriter sw = new StringWriter();
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            
            try {
                
                XMLWriter xmlWriter = new XMLWriter(sw, format);
                
                xmlWriter.write(doc);
            } catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                try {
                    sw.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
    
            return sw.toString();
        }
        
        
    
        public static void test4() {
            Document doc = DocumentHelper.createDocument();
    
            Element rootEle = doc.addElement("sudent");
    
            Element nameEle = rootEle.addElement("name");
            nameEle.setText("张三");
    
            Element ageEle = rootEle.addElement("age");
            ageEle.setText("25");
    
            try {
                StringWriter sw = new StringWriter();
                OutputFormat format = OutputFormat.createPrettyPrint();
                format.setEncoding("utf-8");
                XMLWriter xmlWriter = new XMLWriter(sw, format);
    
                xmlWriter.write(doc);
    
                System.out.println(sw.toString());
            } catch (IOException ex) {
                Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
            }
    
        }
    
        public static void test3() throws DocumentException {
            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + "<books>"
                    + "    <book>"
                    + "        <name>Think in Java</name>"
                    + "        <price>120.0</price>"
                    + "           <chapters>"
                    + "               <c>001</c>"
                    + "               <c>002</c>"
                    + "               <c>003</c>"
                    + "           </chapters>"
                    + "    </book>"
                    + "    <book>"
                    + "        <name>Think in Java2</name>"
                    + "        <price>220.0</price>"
                    + "    </book>"
                    + "</books>";
            Document doc = DocumentHelper.parseText(str);
            Element books = doc.getRootElement();
            List<Element> childEles = books.elements();
            Iterator<Element> iter = childEles.iterator();
            while (iter.hasNext()) {
                Element book = iter.next();
    
                Element name = book.element("name");
                Element price = book.element("price");
    
                System.out.println("name:" + name.getText() + ",price:" + price.getText());
    
                Element chapters = book.element("chapters");
                if (null != chapters) {
                    Iterator<Element> chaptersIter = chapters.elementIterator();
                    if (null != chaptersIter) {
                        while (chaptersIter.hasNext()) {
                            Element c = chaptersIter.next();
                            System.out.println("===>" + c.getText());
                        }
                    }
                }
    
            }
        }
    
        public static void test2() throws DocumentException {
            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + "<books>"
                    + "    <book>"
                    + "        <name>Think in Java</name>"
                    + "        <price>120.0</price>"
                    + "    </book>"
                    + "    <book>"
                    + "        <name>Think in Java2</name>"
                    + "        <price>220.0</price>"
                    + "    </book>"
                    + "</books>";
    
            Document doc = DocumentHelper.parseText(str);
    
            Element books = doc.getRootElement();
    
            List<Element> childEles = books.elements();
            Iterator<Element> iter = childEles.iterator();
            while (iter.hasNext()) {
                Element book = iter.next();
    
                Element name = book.element("name");
                Element price = book.element("price");
    
                System.out.println("name:" + name.getText() + ",price:" + price.getText());
            }
        }
    
        public static void test1() throws DocumentException {
            String str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                    + "<dzswdjz>"
                    + "    <qr_code>"
                    + "   <nsrsbh>nsrsbh</nsrsbh >"
                    + "   <retStatus >retStatus</retStatus>"
                    + "   <img_name>img_name</img_name>"
                    + "      <img_byteString>img_byteString</img_byteString>"
                    + "   </qr_code>"
                    + "</dzswdjz>";
            Document doc = DocumentHelper.parseText(str);
    
            //获取到父节点
            Element dzswdjz = doc.getRootElement();
    
            //定位到qr_code节点
            Element qr_code = dzswdjz.element("qr_code");
    
            Element nsrsbh = qr_code.element("nsrsbh");
            Element retStatus = qr_code.element("retStatus");
            Element img_name = qr_code.element("img_name");
            Element img_byteString = qr_code.element("img_byteString");
    
            System.out.println("nsrsbh:" + nsrsbh.getText());
            System.out.println("retStatus:" + retStatus.getText());
            System.out.println("img_name:" + img_name.getText());
            System.out.println("img_byteString:" + img_byteString.getText());
        }
    }
    

    相关文章

      网友评论

          本文标题:Dom4j的使用

          本文链接:https://www.haomeiwen.com/subject/kkmdrktx.html