jdom解析xml

使用JDOM解析xml

public static void main(String[] args){   
SAXBuilder sb = new SAXBuilder();   
try {   
Document doc = sb.build("myFile.xml");   
Element root = doc.getRootElement();
}catch(Exception e) {
e.printstack();
}
}


如果我们有一个xml文件,用上面的方式解析即可。但是如果我已经拥有一个String类型的拼装好的xml,应该如何用JDOM来解析呢?好像没直接提供此方法,我们可以使用ByteArrayInputStream来完成
代码如下:

public Map<String,Object> parseXML(Map<String,Object> retVal, String xml) throws Exception {
ByteArrayInputStream xmlStream = null;
try {
SAXBuilder builder = new SAXBuilder();
xmlStream = new ByteArrayInputStream(xml.getBytes("GBK"));
Document document = builder.build(xmlStream);
//获取root元素
Element rootElement = document.getRootElement();
paymentQueryResp(rootElement,retVal);
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
log.debug("xml解析完毕Map值:" + retVal + "..............");
return retVal;
}

//采用递归调用将xml中所有的孩子节点放到Map中,key:标签名, value:值
private void paymentQueryResp(Element rootElement, Map<String,Object> retVal) throws DataValidateException{
List<Element> elements = rootElement.getChildren();
for(Element element : elements) {
if(element.getChildren().size() > 0) {
paymentQueryResp(element, retVal);
}else{
//System.err.println(element.getName() + "#" + element.getValue());
retVal.put(element.getName(), element.getValue());
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值