jar准备:dom4j-2.1.1.jar  jaxen-1.1.6.jar

jaxen/jaxen/ Maven依赖写法

<dependency>
  <groupId>jaxen</groupId>
  <artifactId>jaxen</artifactId>
  <version>1.1.6</version>
</dependency>

<dependency>
  <groupId>org.dom4j</groupId>
  <artifactId>com.springsource.org.dom4j</artifactId>
  <version>2.1.1</version>
</dependency>

1 字符串转对象步骤如下:

 1 package xml;
2
3 import org.dom4j.Document;
4 import org.dom4j.DocumentHelper;
5 import org.dom4j.Element;
6 import utils.ClassRoom;
7 import utils.Person;
8
9 import java.util.ArrayList;
10 import java.util.List;
11
12 public class ParseXmlStringToBean {
13
14 private static String getPropetyValue(Document doc, String rootPath, String defaultValue) {
15 if (doc.selectNodes(rootPath).size() == 0) {
16 return defaultValue;
17 }
18 return ((Element) doc.selectNodes(rootPath).get(0)).getText();
19 }
20
21 private static int getPropetyValue(Document doc, String rootPath, int defaultValue) {
22 if (doc.selectNodes(rootPath).size() == 0) {
23 return defaultValue;
24 }
25 return Integer.parseInt(((Element) doc.selectNodes(rootPath).get(0)).getText());
26 }
27
28 private static List<Person> parsePerson(Document doc, String rootPath) {
29 if (doc.selectNodes(rootPath).size() == 0) {
30 return null;
31 }
32 int size = doc.selectNodes(rootPath).size();
33 List<Person> personList = new ArrayList<Person>();
34 for (int i = 0; i < size; i++) {
35 Person person = new Person();
36 person.setName(((Element) doc.selectNodes(rootPath + "/" + "name").get(i)).getText());
37 person.setSex(((Element) doc.selectNodes(rootPath + "/" + "sex").get(i)).getText());
38 person.setAge(Integer.parseInt(((Element) doc.selectNodes(rootPath + "/" + "age").get(i)).getText()));
39 personList.add(person);
40 }
41 return personList;
42 }
43
44 private static ClassRoom parseXmlString(String context) throws Exception {
45 ClassRoom classRoom = new ClassRoom();
46 Document doc = DocumentHelper.parseText(context);
47
48 classRoom.setClassName(getPropetyValue(doc, "/data/className", ""));
49 classRoom.setTotalNum(getPropetyValue(doc, "/data/ret_Code", 0));
50 classRoom.setPersonList(parsePerson(doc, "/data/list/items/item"));
51 return classRoom;
52 }
53
54 public static void main(String[] args) throws Exception {
55 String classContent = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
56 "<data><className>1班</className><totailNum>3</totailNum><list><items><item><name>张三</name><sex>男</sex><age>44</age></item><item><name>李四</name><sex>男</sex><age>42</age></item><item><name>王五</name><sex>男</sex><age>22</age></item></items></list></data>\n";
57
58 parseXmlString(classContent);
59 }
60 }

2 对象转字符串

 1 package xml;
2
3 import org.dom4j.Document;
4 import org.dom4j.DocumentHelper;
5 import org.dom4j.Element;
6 import utils.ClassRoom;
7 import utils.Person;
8
9 import java.util.ArrayList;
10 import java.util.List;
11
12 public class WriteXmlToString {
13
14 private static String writePersonXml(Person person) {
15 Document doc = DocumentHelper.createDocument();
16 doc.setXMLEncoding("GBK");
17
18 Element root = doc.addElement("data");
19 root.addElement("name").addText(person.getName());
20 root.addElement("sex").addText(person.getSex());
21 root.addElement("age").addText(String.valueOf(person.getAge()));
22 return doc.asXML();
23 }
24
25 private static String writeClassXml(ClassRoom classRoom) {
26 Document doc = DocumentHelper.createDocument();
27 doc.setXMLEncoding("GBK");
28
29 Element root = doc.addElement("data");
30 root.addElement("className").addText(classRoom.getClassName());
31 root.addElement("totailNum").addText(String.valueOf(classRoom.getTotalNum()));
32 Element perList = root.addElement("list");
33 Element perItems = perList.addElement("items");
34 for (Person person : classRoom.getPersonList()) {
35 Element perItem = perList.addElement("item");
36 perItem.addElement("name").addText(person.getName());
37 perItem.addElement("sex").addText(person.getSex());
38 perItem.addElement("age").addText(String.valueOf(person.getAge()));
39 }
40 return doc.asXML();
41 }
42
43 public static void main(String[] args) {
44 String content = writePersonXml(new Person("张三", "男", 44));
45 System.out.println(content);
46
47 List<Person> personList = new ArrayList<Person>();
48 personList.add(new Person("张三", "男", 44));
49 personList.add(new Person("李四", "男", 42));
50 personList.add(new Person("王五", "男", 22));
51 ClassRoom classRoom = new ClassRoom("1班", personList.size(), personList);
52 String classContent = writeClassXml(classRoom);
53 System.out.println(classContent);
54 }
55 }

运行结果

<?xml version="1.0" encoding="GBK"?>
<data>
<name>张三</name>
<sex>男</sex>
<age>44</age>
</data>

<?xml version="1.0" encoding="GBK"?>
<data>
<className>1班</className><totailNum>3</totailNum>
<list>
<items>
<item><name>张三</name><sex>男</sex><age>44</age></item>
<item><name>李四</name><sex>男</sex><age>42</age></item>
<item><name>王五</name><sex>男</sex><age>22</age></item>
</items>
</list>
</data>

使用xml4j xml与字符串之间转换的更多相关文章

  1. Python: 在Unicode和普通字符串之间转换

    Unicode字符串可以用多种方式编码为普通字符串, 依照你所选择的编码(encoding): <!-- Inject Script Filtered --> Toggle line nu ...

  2. Python——在Unicode和普通字符串之间转换

    1.1. 问题 Problem You need to deal with data that doesn't fit in the ASCII character set. 你需要处理不适合用ASC ...

  3. 普通字符串与Hex编码字符串之间转换

    import java.io.UnsupportedEncodingException; import org.apache.commons.codec.binary.Hex; public clas ...

  4. char*、string、CString各种字符串之间转换

    参考博客: http://blog.csdn.net/luoweifu/article/details/20242307 http://blog.csdn.net/luoweifu/article/d ...

  5. Flex 日期和字符串之间转换

    字符串转为日期: var dateTime:Date= DateField.stringToDate(deTime, "YYYY-MM-DD");//"YYYY-MM-D ...

  6. jquery的json对象与字符串之间转换

    json对象----- >>字符串 JSON.stringify(obj) json字符串------>>json对象 JSON.parse(string) 公众号 欢迎关注我 ...

  7. c#实现16进制和字符串之间转换的代码

    以下示例演示如何执行下列任务: 获取字符串中每个字符的十六进制值. 获取与十六进制字符串中的每个值对应的字符. 将十六进制 string 转换为整型. 将十六进制 string 转换为浮点型. 将字节 ...

  8. javascript数组与字符串之间转换

    一.数组转字符串(将数组元素用某个字符连接成字符串) var a, b;a = new Array(0,1,2,3,4);b = a.join("-"); 二.字符串转数组(将字符 ...

  9. C# 字节数组和十六进制字符串之间转换的另类写法

    今天从http://www.cnblogs.com/NanaLich/archive/2012/05/24/2516860.html看到的,记录下来 主要是XmlSerializationReader ...

随机推荐

  1. SQL Server 根据树状结构表生成以/号分割的路由字符串

    很多情况下,我们有必要把树形结构进行数据梳理.比如,要方便的过滤出一个父节点下的所有子节点等等... 这个时候,我们可以生成一个路径表字符串,在应用时只需要对该字符串进行索引即可达成目的. 目标:按图 ...

  2. linux系统无法启动,提示give root password for maintenance错误

    电脑的虚拟机安装的是centos6.2操作系统,今天打开虚拟机时候,提示 give root password for maintenance (or type control-D to contin ...

  3. [Swift]数组排序:sort和sorted

    sorted只返回一个数组的有序版本,不修改原数组. sort无返回值,只会修改原数组. 定义一个需要排序的数组,其包含元素.示例只初始化一个Int数组. var arr:[Int] = [Int]( ...

  4. sele nium 模块

    python3 web测试模块selenium   阅读目录 1.selenium安装配置 2.Selenium的基本使用 (1)声明浏览器对象 (2)定位元素 (3)元素对象(element) (4 ...

  5. 2016级算法第六次上机-G.ModricWang likes geometry

    1116 ModricWang likes geometry 思路 难题,非常考察几何知识,放在这里作为计算几何场次的最难的题. 原题地址 原版题解 代码

  6. C#-WebForm-Repeater的灵活运用、ItemCommand的用法-增删改查、如何不适用Repeater来展示数据?

    浏览器页面: 代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Defau ...

  7. i2c_smbs 函数

    i2c_smbus系列函数有: s32 i2c_smbus_read_byte(const struct i2c_client *client); s32 i2c_smbus_write_byte(c ...

  8. Mac 10.12通过Launchd创建自定义服务(基于MySQL 5.7.15的开机自启动)

    在上一篇文章http://www.cnblogs.com/EasonJim/p/6275863.html中安装MySQL时采用的时DMG包的安装步骤页面进行安装的,如果这样安装的MySQL是会开机自启 ...

  9. linux 安装php bz2扩展

    折腾了半天,最大的坑就是我是用lnmp一键安装php环境,php7下面没有ext文件夹,有个include下面虽然有个ext 但是里面没有需要的bz2 也尝试去pecl  和 pear 上面去找  无 ...

  10. python-select异步IO

    #实现多任务在同一个线程切换 #!/usr/bin/python from socket import * from select import * from time import ctime so ...