[转帖] dom4j生成和解析xml文件_Tomcat, WebLogic及J2EE讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  Tomcat, WebLogic及J2EE讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 3777 | 回复: 0   主题: [转帖] dom4j生成和解析xml文件        下一篇 
    本主题由 caohang 于 2013-2-1 16:19:56 取消精华
522080330
注册用户
等级:少校
经验:1478
发帖:79
精华:20
注册:2013-1-18
状态:离线
发送短消息息给522080330 加好友    发送短消息息给522080330 发消息
发表于: IP:您无权察看 2013-1-23 15:06:26 | [全部帖] [楼主帖] 楼主

要生成和解析如下格式的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());
       }
}




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论