解析xml格式的字符串,存入map中
package Test;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;
public class demo111 {
static HashMap<String, Object> result = new HashMap<String, Object>();
public static void main(String[] args) {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+
"<Message>" +
"<Head>" +
"<_TransactionId>1</_TransactionId>" +
"<requestHeader><version>1.0</version><serialNo></serialNo><requestId></requestId><refSerialNo></refSerialNo><requestTime>2015-04-28 10:58:23.040</requestTime><timeOutTime></timeOutTime><channelId></channelId><channelSerialNo></channelSerialNo>" +
"</requestHeader>" +
"<control><requesterName></requesterName><requesterRole>123010003</requesterRole><requesterInsitution></requesterInsitution><requesterId></requesterId><requesterTime>2015-04-28 10:58:23.040</requesterTime><requesterLanguage>124010002</requesterLanguage><requesterLocale></requesterLocale><pageStartIndex></pageStartIndex><pageEndIndex></pageEndIndex><availableResultsCount></availableResultsCount><returnAvailableResultCount></returnAvailableResultCount><isAuthorize></isAuthorize><transCode></transCode>" +
"</control>" +
"</Head>" +
"<Body>" +
"<adminSysId>1001920073</adminSysId>" +
"<adminSysTypeCode>0</adminSysTypeCode>" +
"<custMsgList>" +
"<body001>body001</body001><body002>body002</body002>" +
"</custMsgList>" +
"</Body>" +
"</Message>";
System.out.println(xml);
/***********************解析String****************************/
StringReader read = new StringReader(xml);
InputSource source = new InputSource(read);
SAXBuilder sb = new SAXBuilder();
try {
Document doc = (Document) sb.build(source);
Element root = doc.getRootElement();
result.put(root.getName(),root.getText());
parse(root);
} catch (JDOMException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
}
public static HashMap<String,Object> parse(Element root){
List nodes = root.getChildren();
int len = nodes.size();
if(len==0){
result.put(root.getName(),root.getText());
} else {
for(int i=0;i<len;i++){
Element element = (Element) nodes.get(i);//循环依次得到子元素
result.put(element.getName(),element.getText());
parse(element);
}
}
return result;
}
}