Sandeep
Sandeep

Reputation: 41

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

Upvotes: 1

Views: 5211

Answers (3)

Ray Tayek
Ray Tayek

Reputation: 10003

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

Upvotes: 1

youzhi.zhang
youzhi.zhang

Reputation: 141

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);
           }
    }`

Upvotes: 0

AlexR
AlexR

Reputation: 115328

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.

Upvotes: 3

Related Questions