解析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 result = new HashMap();
public static void main(String[] args) {
String xml = ""+
"" +
"" +
"<_TransactionId>1" +
"1.02015-04-28 10:58:23.040" +
"
" +
"1230100032015-04-28 10:58:23.040124010002" +
"
" +
"" +
"" +
"1001920073" +
"0" +
"" +
"body001body002" +
"
" +
"" +
"
";
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 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 Element element = (Element) nodes.get(i);//循环依次得到子元素
result.put(element.getName(),element.getText());
parse(element);
}
}
return result;
}
}

转载于:https://www.cnblogs.com/wzh0125/p/4462766.html

你可能感兴趣的:(解析xml格式的字符串,存入map中)