首页 > 代码库 > 【dom4j】解析xml为map

【dom4j】解析xml为map

 

dom4j解析xml文件

<?xml version="1.0" encoding="utf-8"?>
<workflows> 
  <queryRequest> 
    <branchId>88037062</branchId>  
    <merSysId>00000317</merSysId>  
    <queryNo>948983692</queryNo>  
    <billType>00</billType>  
    <merBillStat>00</merBillStat>  
    <billDate>201610</billDate>  
    <individualArea>948983692</individualArea> 
  </queryRequest> 
</workflows>

 解析代码:

private static Map<String,String> xml2Map(String xml) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            Document doc = DocumentHelper.parseText(xml);//将xml转为dom对象
            Element root = doc.getRootElement();//获取根节点
            Element element = root.element("queryRequest");//获取名称为queryRequest的子节点
            List<Element> elements = element.elements();//获取这个子节点里面的所有子元素,也可以element.elements("userList")指定获取子元素
             for (Object obj : elements) {  //遍历子元素
                  element = (Element) obj;  
                  map.put(element.getName(), element.getTextTrim());/getName
                 System.out.println(element.getName()+"--"+element.getTextTrim());
             } 
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

 

 

以下这种写法也常见

 

 public  Boolean readStringXml(String xml) {  
        Document doc = null;  
        try {  
            doc = DocumentHelper.parseText(xml); // 将字符串转为XML  
            Element rootElt = doc.getRootElement(); // 获取根节点  
            Iterator<?> iter = rootElt.elementIterator("is_success"); // 获取根节点下的子节点head  
            // 遍历head节点  
            while (iter.hasNext()) {  
                Element recordEle = (Element) iter.next();  
                return recordEle.getText().equals("T")?true:false;
            }  
        } catch (DocumentException e) {  
            e.printStackTrace();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }
        return null;
    }  

 

xml转为map

 

【dom4j】解析xml为map