网站地图    收藏   

主页 > 前端 > javascript >

dom4j生成和解析xml文件

来源:自学PHP网    时间:2014-09-19 14:47 作者: 阅读:

[导读] dom4j生成和解析xml文件 有需要的朋友可参考...

要生成和解析如下格式的xml文件:

 代码如下 复制代码


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

<Message xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <User>
    <id>1</id>
    <name>李寻欢</name>
    <age>30</age>
    <Address>
      <id>1</id>
      <province>广东省</province>
      <city>广州市</city>
      <area>越秀区</area>
      <street>环市东路</street>
    </Address>
  </User>
</Message>  

1、两个数据实体类

    1)User类

 

 代码如下 复制代码

/**
 * @Description: 用户
 */
public class User {
   
    private Long id;
   
    //姓名
    private String name;
    //年龄
    private Integer age;
    //地址
    private Address address;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }
}    

2)Address类

 

 代码如下 复制代码

/**
 *
 * @Description: 地址
 */
public class Address {
   
    private Long id;
    //省份
    private String province;
    //城市
    private String city;
    //区县
    private String area;
    //街道
    private String street;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getStreet() {
        return street;
    }

    public void setStreet(String street) {
        this.street = street;
    }
}

  

2、使用dom4j生成xml和解析xml的工具类

 

 代码如下 复制代码

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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;

/**
 *
 * @Description: Xml生成解析工具
 * @author Luxh
 */
public class XmlUtil {
   
    /**
     * 生成xml文档
     * @param user 用户信息
     * @return
     */
    private static Document generateDocument(User user) {
       
        Document document = DocumentHelper.createDocument();
       
        //添加元素 Message
        Element messageElement = document.addElement("Message");
       
        //给Message元素添加属性 xmlns:xs="http://www.w3.org/2001/XMLSchema"
        messageElement.addAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
       
        //添加元素 User
        Element userElement = messageElement.addElement("User");
       
        //添加User子元素 id
        Element idElement = userElement.addElement("id");
        //给id元素赋值
        idElement.setText(String.valueOf(user.getId()));
       
        //添加User子元素 name
        Element nameElement = userElement.addElement("name");
        //给name元素赋值
        nameElement.setText(user.getName());
       
        //添加User子元素 age
        Element ageElement = userElement.addElement("age");
        //给age元素赋值
        ageElement.setText(String.valueOf(user.getAge()));
       
        //添加User子元素 Address
        Element addressElement = userElement.addElement("Address");
       
        //添加Address子元素 id
        Element addressIdElement = addressElement.addElement("id");
        //给id元素赋值
        addressIdElement.setText(String.valueOf(user.getAddress().getId()));
       
        //添加Address子元素 province
        Element provinceElement = addressElement.addElement("province");
        //给province元素赋值
        provinceElement.setText(user.getAddress().getProvince());
       
        //添加Address子元素 city
        Element cityElement = addressElement.addElement("city");
        //给city元素赋值
        cityElement.setText(user.getAddress().getCity());
       
        //添加Address子元素 area
        Element areaElement = addressElement.addElement("area");
        //给area元素赋值
        areaElement.setText(user.getAddress().getArea());
       
        //添加Address子元素 street
        Element streetElement = addressElement.addElement("street");
        //给street元素赋值
        streetElement.setText(user.getAddress().getStreet());
       
        return document;
    }
   
    /**
     * 生成xml文件
     */
    public static void generateXmlFile(User user) {
       
        Document document = generateDocument(user);
        XMLWriter out = null;
       
        BufferedWriter bw = null;
        OutputStreamWriter osw = null;
        FileOutputStream fos = null;
       
        try {
            File xmlFile = new File("D:/user.xml");//输出xml的路径
            fos = new FileOutputStream(xmlFile);
            osw = new OutputStreamWriter(fos,"UTF-8");//指定编码,防止写中文乱码
            bw = new BufferedWriter(osw);
           
            //对xml输出格式化
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("UTF-8");
            out = new XMLWriter(bw, format);
            out.write(document);
           
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(out != null) {
                    out.close();
                }
                if(bw != null) {
                    bw.close();
                }
                if(osw != null) {
                    osw.close();
                }
                if(fos != null) {
                    fos.close();
                }
               
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
   
    /**
     * 解析xml文件
     * @param xmlFile
     * @return
     * @throws DocumentException
     */
    public static User analyzeXmlFile(File xmlFile) throws DocumentException {
       
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(xmlFile);
        //获取根元素Message
        Element messageElement = document.getRootElement();
       
        //获取Message元素下的子元素
        Iterator<Element> oneLevelElementItor = messageElement.elementIterator();
        Map<String,String> userAttrMap = new HashMap<String,String>();
        Map<String,String> addressAttrMap = new HashMap<String,String>();
       
        while(oneLevelElementItor.hasNext()){
            Element e1 = oneLevelElementItor.next();
            System.out.println("Message子元素:"+e1.getName());
            //获取User元素下的子元素
            Iterator<Element> twoLevelElementItor = e1.elementIterator();
            while(twoLevelElementItor.hasNext()) {
                Element e2 = twoLevelElementItor.next();
                System.out.println("User子元素:"+e2.getName());
                userAttrMap.put(e2.getName(), e2.getText());
               
                //获取Address下的子元素
                if("Address".equals(e2.getName())) {
                    Iterator<Element> threeLevelElementItor = e2.elementIterator();
                    while(threeLevelElementItor.hasNext()) {
                        Element e3 = threeLevelElementItor.next();
                        System.out.println("Address子元素:"+e3.getName());
                        addressAttrMap.put(e3.getName(), e3.getText());
                    }
                   
                }
            }
           
        }
       
        //将解析出来的数据封装成User
        User user = new User();
        user.setId(Long.valueOf(userAttrMap.get("id")));
        user.setName(userAttrMap.get("name"));
        user.setAge(Integer.valueOf(userAttrMap.get("age")));
       
        Address address = new Address();
        address.setId(Long.valueOf(addressAttrMap.get("id")));
        address.setProvince(addressAttrMap.get("province"));
        address.setCity(addressAttrMap.get("city"));
        address.setArea(addressAttrMap.get("area"));
        address.setStreet(addressAttrMap.get("street"));
       
        user.setAddress(address);
        return user;
    }
   
   
}  

  

3、测试

 代码如下 复制代码


import java.io.File;

import org.dom4j.DocumentException;
import org.junit.Test;

public class UserXmlTest {
   
    /**
     * 生成xml文件
     */
    @Test
    public void testGenerateXml() {
       
        //构造一个用户信息
        User user = new User();
        user.setId(1L);
        user.setName("李寻欢");
        user.setAge(30);
       
        Address address = new Address();
        address.setId(1L);
        address.setProvince("广东省");
        address.setCity("广州市");
        address.setArea("越秀区");
        address.setStreet("环市东路");
       
        user.setAddress(address);
       
        XmlUtil.generateXmlFile(user);
    }
   
   
    /**
     * 解析xml文件
     * @throws DocumentException
     */
    @Test
    public void testAnalyzeXmlFile() throws DocumentException {
        File xmlFile = new File("D:/user.xml");
        User user = XmlUtil.analyzeXmlFile(xmlFile);
        System.out.println("user'name is :"+user.getName());
        System.out.println("user'address'province is :"+user.getAddress().getProvince());
    }
}

自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习

京ICP备14009008号-1@版权所有www.zixuephp.com

网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com

添加评论