基于dom4j-1.6.1.jar

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生成xml字符串,以及解析xml字符串的更多相关文章

  1. Java中使用DOM4J来生成xml文件和解析xml文件

    一.前言 现在有不少需求,是需要我们解析xml文件中的数据,然后导入到数据库中,当然解析xml文件也有好多种方法,小编觉得还是DOM4J用的最多最广泛也最好理解的吧.小编也是最近需求里遇到了,就来整理 ...

  2. XML基础+Java解析XML +几种解析方式的性能比较

    XML基础+Java解析XML 一:XML基础 XML是什么: 可扩展的标记语言 XML能干什么: 描述数据.存储数据.传输(交换)数据. XML与HTML区别: 目的不一样 XML 被设计用来描述数 ...

  3. xml语法、DTD约束xml、Schema约束xml、DOM解析xml

    今日大纲 1.什么是xml.xml的作用 2.xml的语法 3.DTD约束xml 4.Schema约束xml 5.DOM解析xml 1.什么是xml.xml的作用 1.1.xml介绍 在前面学习的ht ...

  4. python 之模块之 xml.dom.minidom解析xml

    # -*- coding: cp936 -*- #python 27 #xiaodeng #python 之模块之 xml.dom.minidom解析xml #http://www.cnblogs.c ...

  5. Java利用dom4j生成xml文件、解析XML

    package com.fq.fanqi; import java.io.File;import java.io.FileWriter;import java.io.IOException;impor ...

  6. 在C#中使用属性控制 XML 序列化来解析XML

    今天需要解析一个XML,这个XML和一般情况用.NET的序列化出来的格式不太一样. 我就又补习了一下. 分享一下学习成果吧. 示例代码下载: http://download.csdn.net/deta ...

  7. PHP通过XML报文格式的POST请求方式,与第三方接口交互(发送xml,获取XML,并解析xml步骤)

    开发者端:发送请求,并接收结果 <?php // 下面的demo,实现的功能如下: // 1-开发者需要判断一个用户是否存在,去请求第三方接口. // 2-与第三方接口的通信,是以xml格式传送 ...

  8. 创建xml文件、解析xml文件

        1.创建XML文件: import codecs import xml.dom.minidom doc=xml.dom.minidom.Document() print doc root=do ...

  9. ElementTree 解析xml(minidom解析xml大文件时,MemoryError)

    在使用minido解析xml文件时,因为文件过大,结果报错MemoryError.查询后得知是因为minidom在解析时是将所有文件放到内存里的,很占用内存,所以要考虑换一种方法来处理xml文件.   ...

  10. python xml.dom模块解析xml

    1. 什么是xml?有何特征? xml即可扩展标记语言,它可以用来标记数据.定义数据类型,是一种允许用户对自己的标记语言进行定义的源语言. 例子:del.xml <?xml version=&q ...

随机推荐

  1. Cgroup - Linux 内存资源管理

    Hi ,我是 Zorro .这是我的微博地址,我会不定期在这里更新文章,如果你有兴趣,可以来关注我呦. 另外,我的其他联系方式: Email: mini.jerry@gmail.com QQ: 300 ...

  2. 【Cocos2d-X开发学习笔记】第10期:渲染框架之几何图形的绘制

    本系列学习教程使用的是cocos2d-x-2.1.4(最新版为3.0alpha0-pre) ,PC开发环境Windows7,C++开发环境VS2010 一.图形的绘制 有时为了调试游戏,我们常常会需要 ...

  3. HTTP学习笔记7-消息报头

    41,消息报头-实体报头 请求和响应消息可以传送一个实体.一个实体由实体报头域和实体正文组成,在大多数情况下,实体正文就是请求消息中的请求正文或者响应消息中的响应正文.但是在发送时,并不是说实体报头域 ...

  4. 集群中几种session同步解决方案的比较

    1. 客户端cookie加密 .比较好的方法是自己采用cookie机制来实现一个session,在应用中使用此session实现. 问题:session中数据不能太多,最好只有个用户id. Sessi ...

  5. 1033 - Merging Maps

    Pictures taken from an airplane or satellite of an ar ea to be mapped are often of sufficiently high ...

  6. VNC 黑屏

    参考资料: http://blog.sina.com.cn/s/blog_57edaf600100serf.html http://www.programgo.com/article/43581885 ...

  7. 【iOS开发】emoji表情的输入思路

    1.自定义一个表情包类继承NSTextAttachment #import <UIKit/UIKit.h> /** 表情包的自定义类*/ @interface EmojiTextAttac ...

  8. Visual Studio写的项目在 IIS 服务器上运行的两种简单方法

    首先需要PC上开启了IIS服务,相关方法网上很多,也很简单 第一种:直接在项目中操作 1.创建一个项目,然后右击选中项目,右击,单击属性,打开项目属性标签页面 如图,选择Web标签,在服务器栏目中选中 ...

  9. 解决 iOS webkit 使用CSS动画时闪烁的问题

    -webkit-backface-visibility: hidden;

  10. android:http下载文件并保存到本地或SD卡

    想把文件保存到SD卡中,一定要知道SD卡的路径,获取SD卡路径: Environment.getExternalStorageDirectory() 另外,在保存之前要判断SD卡是否已经安装好,并且可 ...