dom4j组装xml 以及解析xml

dom4j组装xml 以及解析xml:

1.下载dom4j的jar包,地址:https://dom4j.github.io/

2.java代码:

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;

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.SAXReader;
import org.dom4j.io.XMLWriter;
import org.xml.sax.SAXException;

/**
 * dom4j解析xml
 * @author lyc
 *
 */
public class DOM4J {

    public static void main(String[] args) {
        DOM4J dom4j= new DOM4J();
        try {
            //生成xml
            dom4j.objectToXml();
            //解析xml
            //dom4j.xmlToObject();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
     // 获取并解析xml格式文件为object
     public void xmlToObject() throws ParserConfigurationException, DocumentException, SAXException, IOException{
             /**
              * 1.解析xml文件
              */
            SAXReader saxReader = new SAXReader();
            //将获取的xml 转化为document 文档
            //这里使用了File当然也可以使用URL()从指定url获取xml并进行解析
            //document从文件中解析出来
            //Document document = saxReader.read(new File("src/1.xml"));
            
            /**
              * 2.解析xml字符串
              */
            //解析xml字符串
            //document从字符串中解析出来
            String xml = "<?xml version='1.0' encoding='UTF-8'?><student name='zhangsan'><courses><yuwen>语文</yuwen><shuxue>数学</shuxue></courses><courses><yingyu>英语</yingyu><huaxue>化学</huaxue></courses></student>";
            Document document = DocumentHelper.parseText(xml); // 将字符串转为XML
            // 获取根元素
            Element root = document.getRootElement();
            // 根元素名称
            System.out.println("reservationList Root----: " + root.getName());
            
            // 获取所有子元素
            List<Element> childList = root.elements();
            
            //解析xml串
            System.out.println(childList.get(0).element("yuwen").getTextTrim());
            System.out.println("courses child 长度:" + childList.size());
            for(Element e : childList){
                List<Element> list = e.elements();
                for(Element e1 : list){
                    System.out.println(e1.getTextTrim());
                }
                System.out.println("==========");
            }
            
            System.out.println("total reservation child count: " + childList.size());
            System.out.println("第一个reservation的quotationId节点值:"+childList.get(0).element("quotationId").getTextTrim());
            for(Element e : childList){
                /*Element helloElement = e.element("quotationId");
                System.out.println(helloElement.getTextTrim());*/
                
                Element insurantListE = e.element("insurantList");
                List<Element> insurantList = insurantListE.elements();
                System.out.println("total insurant child count: " + insurantList.size());
                for(Element e1 : insurantList){
                    Element helloElement1 = e1.element("insurantName");
                    System.out.println(helloElement1.getTextTrim());
                }
            }
    
            /*// 获取特定名称的子元素
            List<Element> childList2 = root.elements("reservation");
            Element helloElement = root.element("quotationId");
            System.out.println("hello child: " + childList2.size());
            // 获取特定名称的子元素的值
            System.out.println("hello----"+childList2.get(0).getText());
            System.out.println("hello----"+helloElement.getText().trim());
            System.out.println("迭代输出-----------------------");*/
            
            // 迭代输出
            /*for (Iterator iter = root.elementIterator(); iter.hasNext();)
            {   // 获取根目录下的元素
                Element e = (Element) iter.next();
                // 获取元素对应的值
                System.out.println(e.getText());
                // 元素的属性个数
                System.out.println(e.attributeCount());
                //获取元素的第一个属性的名称
                System.out.println(e.attribute(0).getName());
                //获取元素的第一个属性的值
                System.out.println(e.attribute(0).getValue());
                //获取元素的第二个属性的名称
                System.out.println(e.attribute(1).getName());
              //获取元素的第二个属性的值
                System.out.println(e.attribute(1).getValue());
                //按照属性名称获取属性值
                System.out.println("are you ok :"+e.attributeValue("age"));
                System.out.println("are you ok :"+e.attributeValue("name"));
            }*/
            
            // 使用DOMReader将xml转化为object
            /*System.out.println("用DOMReader-----------------------");
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            // 注意要用完整类名
            //将获取的xml 转化为document 文档
            org.w3c.dom.Document document2 = db.parse(new File("F:/student2.xml"));
    
            DOMReader domReader = new DOMReader();
    
            // 将JAXP的Document转换为dom4j的Document
            Document document3 = domReader.read(document2);
    
            Element rootElement = document3.getRootElement();
    
            System.out.println("Root: " + rootElement.getName());*/
        }
     
      // 将对象组装成xml格式文件并保存
     public void objectToXml ()throws Exception{
        // 第一种方式:创建文档,并创建根元素
        // 创建文档:使用了一个Helper类
        Document document = DocumentHelper.createDocument();
        // 创建根节点并添加进文档
        Element root = DocumentHelper.createElement("student");
        document.setRootElement(root);

        // 第二种方式:创建文档并设置文档的根元素节点
        Element root2 = DocumentHelper.createElement("student");
        Document document2 = DocumentHelper.createDocument(root2);
        // 给元素添加属性
        root2.addAttribute("name", "zhangsan");
        
        Element e = root2.addElement("courses");
        /*Map<String,Object> map1 = new HashMap<String,Object>();
        Map<String,Object> map2 = new HashMap<String,Object>();
        List<Map<String,Object>> list = new ArrayList();
        
        map2.put("yuwen", "语文");
        map2.put("shuxue", "数学");
        list.add(map1);
        list.add(map2);*/
        
        /*for(Map map : list){
            Element courseElement = e.addElement(map.entrySet().iterator().next().toString());
            courseElement.setText(map.get(map.entrySet().iterator().next().toString()).toString());
        }*/
        
        Element yuwenElement = e.addElement("yuwen");
        Element shuxueElement = e.addElement("shuxue");
        
        yuwenElement.setText("语文");
        shuxueElement.setText("数学");
        
        /**
         * 1.生成xml字符串
         */
        //生成xml字符串方式一:
        String xmlText = document2.asXML();
        System.out.println(xmlText);
        
        //生成xml字符串方式二:
        /*OutputFormat format1 = OutputFormat.createCompactFormat(); //createPrettyPrint() 层次格式化
        StringWriter writer = new StringWriter();
        XMLWriter output = new XMLWriter(writer, format1);
        output.write(document);
        System.out.println();
        System.out.println("xmlToString:"+writer.toString());*/
        
        /**
         * 2.生成xml文件
         */
        /* // 添加子节点:add之后就返回这个元素
        Element helloElement = root2.addElement("hello");
        Element worldElement = root2.addElement("world");
        //给元素添加属性key-value
        worldElement.addAttribute("age","12");
        worldElement.addAttribute("name","www");
        helloElement.addAttribute("age","13");
        helloElement.addAttribute("name","wws");
        //元素的节点的值
        helloElement.setText("hello Text");
        worldElement.setText("world text");*/
        // 输出
        // 输出到控制台
        XMLWriter xmlWriter = new XMLWriter();
        xmlWriter.write(document);

        //输出到文件
        //其中的"  "表示格式,true参数表示另起一行,gb2312表示编码,如果不写这个参数则默认utf-8编码
        //1、OutputFormat format=new OutputFormat("  ",true,"gb2312"); 
        //生成压缩格式、紧凑格式的xml  其中的compactFormat 翻译:压缩格式    
        //2、 OutputFormat format = OutputFormat.createCompactFormat();
        //调用静态方法创建一个没有格式的打印方式
        //3、 OutputFormat format = OutputFormat.createPrettyPrint();    
        //format.setEncoding("gb2312");  // 设置编码
        OutputFormat format = new OutputFormat("  ", true);// 设置缩进为2个空格,并且另起一行为true
        XMLWriter xmlWriter2 = new XMLWriter(
                new FileOutputStream("C:/Users/lyc/Desktop/student1.xml"), format);
        xmlWriter2.write(document2);
        xmlWriter2.flush();
        xmlWriter2.close();

        // 另一种输出方式,记得要调用flush()方法,否则输出的文件中显示空白,调用close() 方法释放资源
        XMLWriter xmlWriter3 = new XMLWriter(new FileWriter("C:/Users/lyc/Desktop/student2.xml"),
                format);
        xmlWriter3.write(document2);
        xmlWriter3.flush();
        xmlWriter3.close();
     }

}

 

3.需要解析的xml内容:
1.xml:(自己定义xml文件),例如:

<?xml version="1.0" encoding="UTF-8"?>

<student name="zhangsan"> <courses> <yuwen>语文</yuwen> <shuxue>数学</shuxue> </courses> </student>

 

4.生成xml文件:

student1.xml:

<?xml version="1.0" encoding="UTF-8"?>

<student name="zhangsan">
  <courses>
    <yuwen>语文</yuwen>
    <shuxue>数学</shuxue>
  </courses>
</student>

student2.xml:

<?xml version="1.0" encoding="UTF-8"?>

<student name="zhangsan">
  <courses>
    <yuwen>语文</yuwen>
    <shuxue>数学</shuxue>
  </courses>
</student>

 

转载于:https://www.cnblogs.com/super-chao/p/7779078.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值