xml 转map dom4j

http://ziyu-1.iteye.com/blog/469003

传过来一个xml文件,需要转换成Map,能够应对不用结构的xml,而不是只针对固定格式的xml. 
转换规则: 
1.主要是Map与List的互相嵌套 
2.同名称的节点会被装进List

如下面的xml文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <GmMail>
 3     <template_id>2</template_id>
 4     <to_address>[email protected]</to_address>
 5     <to_alias>tom</to_alias>
 6     <message>XML-未来世界 Message</message>
 7     <recipient_name>xml-tom</recipient_name>
 8     <send_address>[email protected]</send_address>
 9     <sender_comp_name>xml-gm</sender_comp_name>
10     <subject>xml-hello guys</subject>
11     <selected_items>
12         <item_group>
13             <item_url>http://china.gm.com</item_url>
14             <item_name>gm中文站</item_name>
15             <item_desc>gm中文站desc</item_desc>
16             <item_desc2>gm中文站desc2</item_desc2>
17             <item_desc3>gm中文站desc3</item_desc3>
18             <item_desc4>gm中文站desc4</item_desc4>
19         </item_group>
20         <items_source>products</items_source>
21         <item_group>
22             <item_url>http://www.gm.com</item_url>
23             <item_name>gm</item_name>
24             <item_desc>gmdesc</item_desc>
25         </item_group>
26     </selected_items>
27     <attachments>
28         <attachment-group>
29             <attachment_url>
30                 http://china.gm.com/pics/com.cn.gm/story/frsc.jpg
31             </attachment_url>
32             <attachment_name>黄晓豫</attachment_name>
33             <attachment_desc>
34                 <desc1>attach-desc1</desc1>
35                 <desc2>attach-desc2</desc2>
36                 <desc3>attach-desc3</desc3>
37                 <desc4>attach-desc4</desc4>
38             </attachment_desc>
39         </attachment-group>
40         <attachment-group>
41             <attachment_url>
42                 http://china.gm.com/pics/com.cn.gm/story/wr.jpg
43             </attachment_url>
44             <attachment_name>张中汉</attachment_name>
45             <attachment_desc>
46                 <desc1>attach-desc1</desc1>
47                 <desc2>attach-desc2</desc2>
48             </attachment_desc>
49             <attachment_desc>
50                 <desc1>attach-desc1</desc1>
51                 <desc2>attach-desc2</desc2>
52             </attachment_desc>
53         </attachment-group>
54     </attachments>
55     <desc_group>
56         <desc_item>desc_item_1</desc_item>
57         <desc_item>desc_item_2</desc_item>
58         <desc_item>desc_item_3</desc_item>
59         <desc_item>desc_item_4</desc_item>
60         <desc_item>desc_item_5</desc_item>
61     </desc_group>
62 </GmMail>

转换后的的Map(转换成字符串的效果):

{message=XML-未来世界 Message, selected_items={items_source=products, item_group=[{item_name=gm中文站, item_desc=gm中文站desc, item_desc2=gm中文站desc2, item_desc4=gm中文站desc4, item_url=http://china.gm.com, item_desc3=gm中文站desc3}, {item_name=gm, item_desc=gmdesc, item_url=http://www.gm.com}]}, to_alias=tom, desc_group={desc_item=[desc_item_1, desc_item_2, desc_item_3, desc_item_4, desc_item_5]}, sender_comp_name=xml-gm, subject=xml-hello guys, [email protected], template_id=2, attachments={attachment-group=[{attachment_url=http://china.gm.com/pics/com.cn.gm/story/frsc.jpg, attachment_name=黄晓豫, attachment_desc={desc3=attach-desc3, desc4=attach-desc4, desc1=attach-desc1, desc2=attach-desc2}}, {attachment_url=http://china.gm.com/pics/com.cn.gm/story/wr.jpg, attachment_name=张中汉, attachment_desc=[{desc1=attach-desc1, desc2=attach-desc2}, {desc1=attach-desc1, desc2=attach-desc2}]}]}, recipient_name=xml-tom, [email protected]}

xml处理用的dom4j

下面是实现转换的主要类XmlUtils:

 1 package xml.dom4j;
 2
 3 import java.util.ArrayList;
 4 import java.util.HashMap;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 import java.util.Map;
 8
 9 import org.dom4j.Document;
10 import org.dom4j.Element;
11
12 public class XmlUtils {
13
14     public static Map<String, Object> Dom2Map(Document doc){
15         Map<String, Object> map = new HashMap<String, Object>();
16         if(doc == null)
17             return map;
18         Element root = doc.getRootElement();
19         for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {
20             Element e = (Element) iterator.next();
21             //System.out.println(e.getName());
22             List list = e.elements();
23             if(list.size() > 0){
24                 map.put(e.getName(), Dom2Map(e));
25             }else
26                 map.put(e.getName(), e.getText());
27         }
28         return map;
29     }
30
31
32     public static Map Dom2Map(Element e){
33         Map    map = new HashMap();
34         List list = e.elements();
35         if(list.size() > 0){
36             for (int i = 0;i < list.size(); i++) {
37                 Element iter = (Element) list.get(i);
38                 List mapList = new ArrayList();
39
40                 if(iter.elements().size() > 0){
41                     Map m = Dom2Map(iter);
42                     if(map.get(iter.getName()) != null){
43                         Object obj = map.get(iter.getName());
44                         if(!obj.getClass().getName().equals("java.util.ArrayList")){
45                             mapList = new ArrayList();
46                             mapList.add(obj);
47                             mapList.add(m);
48                         }
49                         if(obj.getClass().getName().equals("java.util.ArrayList")){
50                             mapList = (List) obj;
51                             mapList.add(m);
52                         }
53                         map.put(iter.getName(), mapList);
54                     }else
55                         map.put(iter.getName(), m);
56                 }
57                 else{
58                     if(map.get(iter.getName()) != null){
59                         Object obj = map.get(iter.getName());
60                         if(!obj.getClass().getName().equals("java.util.ArrayList")){
61                             mapList = new ArrayList();
62                             mapList.add(obj);
63                             mapList.add(iter.getText());
64                         }
65                         if(obj.getClass().getName().equals("java.util.ArrayList")){
66                             mapList = (List) obj;
67                             mapList.add(iter.getText());
68                         }
69                         map.put(iter.getName(), mapList);
70                     }else
71                         map.put(iter.getName(), iter.getText());
72                 }
73             }
74         }else
75             map.put(e.getName(), e.getText());
76         return map;
77     }
78
79 }

下面是一个创建xml的类(不重要,可以忽略,只是用来生成一个xml以便测试,可以自己写)

 1 package xml.dom4j;
 2
 3 import org.dom4j.Document;
 4 import org.dom4j.DocumentHelper;
 5 import org.dom4j.Element;
 6
 7 public class CreateXml {
 8
 9     /**
10      * @param args
11      */
12     public static void main(String[] args) {
13         // TODO Auto-generated method stub
14
15     }
16
17     public Document createXml(){
18         Document doc = DocumentHelper.createDocument();
19         Element e = doc.addElement("GmMail");
20         e.addElement("template_id").setText("2");
21         e.addElement("to_address").setText("[email protected]");
22         e.addElement("to_alias").setText("tom");
23         e.addElement("message").setText("XML-未来世界 Message");
24         e.addElement("recipient_name").setText("xml-tom");
25         e.addElement("send_address").setText("[email protected]");
26         e.addElement("sender_comp_name").setText("xml-gm");
27         e.addElement("subject").setText("xml-hello guys");
28         Element Selecteditems = e.addElement("selected_items");
29
30                 Element itemsGroup = Selecteditems.addElement("item_group");
31             //Element item = itemsGroup.addElement("item");
32                     itemsGroup.addElement("item_url").setText("http://china.gm.com");
33                     itemsGroup.addElement("item_name").setText("gm中文站");
34                     itemsGroup.addElement("item_desc").setText("gm中文站desc");
35                     itemsGroup.addElement("item_desc2").setText("gm中文站desc2");
36                     itemsGroup.addElement("item_desc3").setText("gm中文站desc3");
37                     itemsGroup.addElement("item_desc4").setText("gm中文站desc4");
38                 Selecteditems.addElement("items_source").setText("products");
39                 itemsGroup = Selecteditems.addElement("item_group");
40                     itemsGroup.addElement("item_url").setText("http://www.gm.com");
41                     itemsGroup.addElement("item_name").setText("gm");
42                     itemsGroup.addElement("item_desc").setText("gmdesc");
43         Element attachment = e.addElement("attachments");
44             Element attachmentGroup =    attachment.addElement("attachment-group");
45                 attachmentGroup.addElement("attachment_url").setText("http://china.gm.com/pics/com.cn.gm/story/frsc.jpg");
46                 attachmentGroup.addElement("attachment_name").setText("黄晓豫");
47                     Element attachmentDesc = attachmentGroup.addElement("attachment_desc");
48                     attachmentDesc.addElement("desc1").setText("attach-desc1");
49                     attachmentDesc.addElement("desc2").setText("attach-desc2");
50                     attachmentDesc.addElement("desc3").setText("attach-desc3");
51                     attachmentDesc.addElement("desc4").setText("attach-desc4");
52             attachmentGroup =    attachment.addElement("attachment-group");
53                 attachmentGroup.addElement("attachment_url").setText("http://china.gm.com/pics/com.cn.gm/story/wr.jpg");
54                 attachmentGroup.addElement("attachment_name").setText("张中汉");
55                     attachmentDesc = attachmentGroup.addElement("attachment_desc");
56                         attachmentDesc.addElement("desc1").setText("attach-desc1");
57                         attachmentDesc.addElement("desc2").setText("attach-desc2");
58                     attachmentDesc = attachmentGroup.addElement("attachment_desc");
59                         attachmentDesc.addElement("desc1").setText("attach-desc1");
60                         attachmentDesc.addElement("desc2").setText("attach-desc2");
61         Element descGroup = e.addElement("desc_group");
62             descGroup.addElement("desc_item").setText("desc_item_1");
63             descGroup.addElement("desc_item").setText("desc_item_2");
64             descGroup.addElement("desc_item").setText("desc_item_3");
65             descGroup.addElement("desc_item").setText("desc_item_4");
66             descGroup.addElement("desc_item").setText("desc_item_5");
67         return doc;
68     }
69 }

下面是main调用类:

 1 package xml.dom4j;
 2
 3 import java.util.Map;
 4
 5 import org.dom4j.Document;
 6
 7 public class Demo {
 8
 9     public static void main(String[] args){
10         CreateXml create = new CreateXml();
11         Document doc = create.createXml();
12         String strXml = doc.asXML();
13         System.out.println(strXml);
14
15         Map map = XmlUtils.Dom2Map(doc);
16
17         System.out.println(map.toString());
18     }
19
20 }
时间: 2024-10-14 13:49:14

xml 转map dom4j的相关文章

【dom4j】解析xml为map

dom4j解析xml文件 <?xml version="1.0" encoding="utf-8"?> <workflows> <queryRequest> <branchId>88037062</branchId> <merSysId>00000317</merSysId> <queryNo>948983692</queryNo> <billType&

xml转为Map集合以及对象转化为xml

package com.fang.util; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader

java 解析xml字符串用dom4j

package com.smsServer.Dhst; 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 com.common.object.

Java xml和map,list格式的转换-摘抄

import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import net.sf.json.JSON; import net.sf.json.JSONSerializer;

XML转换为Map通用算法实现(Stax实现)

目前项目中需要将XML转换为Map,下面给出了自己的代码实现.请各路大神提供更好的代码实现. 场景: 在项目中需要解析XML文本字符串,需要将XML文本字符串映射为Map格式的对象. 需求: 1.为了提高性能,需要使用Stax进行解析 2.Map结构内部需要支持List.Map.String三种数据格式 示例: 例一: * 字符串:<name>BurceLiu</name><age>18</age> * 转换为的Map结构:{age=18, name=Bur

xml与map互转

/**  * 将Map转为XML,默认root标签为PACKET:  * 由于List中的元素没有名称,默认将List的名称_LIST>部分替换为_INFO>,作为List中元素的名字:  * 暂不考虑List中的元素也是List的情况.  * @param version 例如1.0  * @param encoding 例如UTF-8或者GBK  * @param packetType 例如REQUEST或者RESPONSE  * @param requestType 例如N01  * @

解析xml报文,xml与map互转

这段时间写了一个关于xml报文的工具类,做一下具体的讲解: xml文本 <NTMMessage version="1.03"> <NTMHeader> <MessageID>1711030000054</MessageID> <MessageSource> <SystemID>MNLN</SystemID> <Location>CITIC</Location> <UserI

dom4j解析Xml,dom4j解析带命名空间的Xml内容,dom4j解析xml为实体类

首先引入maven: <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</arti

XML文件解析-DOM4J方式和SAX方式

最近遇到的工作内容都是和xml内容解析相关的. 1图片数据以base64编码的方式保存在xml的一个标签中,xml文件通过接口的方式发送给我,然后我去解析出图片数据,对图片进行进一步处理. 2.xml内容保存在blob字段中,然后jdbc读取blob字段获取xml内容进行解析. 解析的方法挺简单的,网上有很多种,主要有SAX,DOM4J等. 先来揭晓一下DOM4J是如何解析xml文件的,话不多少,直接上码. /** * 获取xml文件绝对路径 */ private String getFileP