jaxb可以自定义序列化方式,高手指点自己写了一个Adapter,可以实现要求了,附上代码
有帮助
01 | public class DataXmlAdapter extends XmlAdapter<Object, List<Map<String, String>>> { |
02 |
03 | /** |
04 | * 序列化方法。 |
05 | * |
06 | * 把java bean转换成Element,方便JAXB按照指定格式序列化。 |
07 | */ |
08 | @Override |
09 | public Object marshal(List<Map<String, String>> rows) throws Exception { |
10 | // TODO Auto-generated method stub |
11 | DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); |
12 | Document document = builder.newDocument(); |
13 | Element rootEle = document.createElement( "rows" ); |
14 | |
15 | for (Map<String, String> row:rows){ |
16 | Element rowEle = document.createElement( "row" ); |
17 | |
18 | Iterator<Entry<String, String>> itera = row.entrySet().iterator(); |
19 | while (itera.hasNext()) { |
20 | Entry<String, String> entry = itera.next(); |
21 | String key = entry.getKey(); |
22 | String value = entry.getValue(); |
23 | if (key == null || key.equals( "" )) { |
24 | continue ; |
25 | } |
26 | if (value == null ) { |
27 | value = "" ; |
28 | } |
29 | Element detailEle = document.createElement(key); |
30 | detailEle.setTextContent(value); |
31 | rowEle.appendChild(detailEle); |
32 | } |
33 | rootEle.appendChild(rowEle); |
34 | } |
35 | document.appendChild(rootEle); |
36 | return rootEle; |
37 | } |
38 |
39 | /** |
40 | * 反序列化方法。 |
41 | * |
42 | * 把Element转换成java bean。 |
43 | */ |
44 | @Override |
45 | public List<Map<String, String>> unmarshal(Object datas) throws Exception { |
46 | // TODO Auto-generated method stub |
47 | if (datas== null ){ |
48 | return null ; |
49 | } |
50 | NodeList rowlist = ((Element)datas).getChildNodes(); |
51 | if (rowlist == null ){ |
52 | return null ; |
53 | } |
54 | int rowCount = rowlist.getLength(); |
55 | if (rowCount == 0 ){ |
56 | return null ; |
57 | } |
58 | |
59 | List<Map<String, String>> result = new ArrayList<Map<String,String>>(); |
60 | for ( int i = 0 ; i<rowCount; i++){ |
61 | Node rowNode = rowlist.item(i); |
62 | if (! "detail" .equals(rowNode.getNodeName())){ |
63 | continue ; |
64 | } |
65 | |
66 | NodeList detailList = rowNode.getChildNodes(); |
67 | if (detailList == null ){ |
68 | continue ; |
69 | } |
70 | int detailCount = detailList.getLength(); |
71 | if (detailCount == 0 ){ |
72 | continue ; |
73 | } |
74 | |
75 | Map<String, String> detailMap = new HashMap<String, String>(); |
76 | for ( int j = 0 ; j < detailCount; j++){ |
77 | Node detailNode = detailList.item(j); |
78 | String key = detailNode.getNodeName(); |
79 | String value = detailNode.getTextContent(); |
80 | if (key == null || "" .equals(key)){ |
81 | continue ; |
82 | } |
83 | detailMap.put(key, value); |
84 | } |
85 | result.add(detailMap); |
86 | } |
87 | return result; |
88 | } |
89 |
90 | } |