XML:DE轉換成Map.
再幫忙提供一個逆轉的方法。多謝大家。
屬性別丟啊
自己弄出來 了。csdn界面現在換的都不知道該點哪裡。真不習慣。
package cn.jsfund.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.collections.map.LinkedMap;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import cn.jsfund.web.Validation;
/**
@time 2013-07-24
*/
public class XMLUtil {
private static final String SEPARATOR = " ";
/**
@return map
*/
public static Map xml2Map(String xmlStr) {
Map map = new LinkedHashMap();
try {
Document doc;
doc = DocumentHelper.parseText(xmlStr);
Element rootElement = doc.getRootElement();
xml2Map(rootElement, map);
return map;
} catch (DocumentException e) {
e.printStackTrace();
}
return null;
}
/**
/**
/**
private static void map2Xml(StringBuffer sbf, Map map) {
Set s = map.entrySet();
Iterator i = s.iterator();
StringBuffer childSbf = new StringBuffer();
while(i.hasNext()){
Entry e = (Entry) i.next();
String key = (String) e.getKey();
if(key.indexOf("@") >= 0){
continue;
}
if(key != null){
childSbf.append("<").append(key);
}
String attr = "@" + key;
Map attrMap = (Map) map.get(attr);
if(null != attrMap){
Set attrSet = attrMap.entrySet();
Iterator attrIterator = attrSet.iterator();
while(attrIterator.hasNext()){
Entry attrEntry = (Entry) attrIterator.next();
String attrKey = (String) attrEntry.getKey();
String attrValue = (String) attrEntry.getValue();
childSbf.append(SEPARATOR).append(attrKey).append("=").append("\"").append(attrValue).append("\"");
}
}
childSbf.append(">");
Object value = e.getValue();
if(value instanceof List){
List list = (List) value;
for(int j = 0; j
Map valueMap = (Map) list.get(j);
map2Xml(childSbf,valueMap);
}
}else if(value instanceof Map){
Map valueMap = (Map) value;
map2Xml(childSbf, valueMap);
}else{
if(null != value){
childSbf.append(value);
}else{
childSbf.append("");
}
}
if(key != null){
childSbf.append("").append(key).append(">");
}
}
sbf.append(childSbf);
}
public static void main(String[] args) {
String xmlStr6 = "";
Map map6 = xml2Map(xmlStr6);
System.out.println(map6.toString());
String result = map2Xml(map6);
System.out.println(result);
}
}