简体   繁体   中英

how convert XML to List<Map>

I have a XML data like below given Example..

<EMP>
   <PERSONAL_DATA>
     <EMPLID>AA0001</EMPLID>
     <NAME>Adams<NAME>
   </PERSONAL_DATA>
   <PERSONAL_DATA>
     <EMPLID>AA0002<EMPLID>
     <NAME>Paul<NAME>
    </PERSONAL_DATA>
</EMP>

I want to store information about each employee in a Map(KEY,VALUE) KEY=tagname, VALUE=value and want to create a LIST for all employee using XPATH in java. how i Do? Please suggest Thanks

You can use JAXB.

I can see at least 2 solution. First is: create class PersonalData with fields emplid and name . Mark them with @XmlElement annotations. Parse your XML. This will create collection of instances of PersonalData . Now iterate over this collection and create map if you really need it.

But you can map XML to map directly. Take a look on the following blog .

you can use the normal jaxp stuff or try groovy:

String xml='''<EMP>
   <PERSONAL_DATA>
     <EMPLID>AA0001</EMPLID>
     <NAME>Adams</NAME>
   </PERSONAL_DATA>
   <PERSONAL_DATA>
     <EMPLID>AA0002</EMPLID>
     <NAME>Paul</NAME>
    </PERSONAL_DATA>
</EMP>
'''
Node parsed=new XmlParser().parseText(xml)
List<Map> list=[]
parsed.each {
    Map<String,String> map=[:]
    it.children().each {
        map[it.name()]=it.value()[0]
        println "${it.name()} ${it.value()[0]}"
    }
    list.add(map)
}
println list

Why use the XPATH? `String expression = "//EMP/PERSONAL_DATA/*";
XPathExpression expr = xpath.compile(expression);

     Object result = expr.evaluate(doc, XPathConstants.NODESET); 
     NodeList nodes = (NodeList) result;  

     List<Map> list = new ArrayList<Map>();

     for (int i = 0; i < nodes.getLength(); i++) {  
           Node node = nodes.item(i);
           Map<String,String> nodeMap = new HashMap<String,String>();
           if (node.getNodeName()!=null){                  
              nodeMap.put(node.getNodeName(), node.getTextContent());
              list.add(nodeMap);
           }
    }`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM