how to parse xml to hashmap?

后端 未结 3 853
北荒
北荒 2021-01-12 20:17

I have an example of an xml I want to parse

 

a
3条回答
  •  心在旅途
    2021-01-12 20:33

    I can not resist to present a much shorter solution using XMLBeam that works with any number of "detail-x" subelements.

    public class Tetst {
    
    @XBDocURL("resource://test.xml")
    public interface Projection {
        @XBRead("name()")
        String getName();
    
        @XBRead("./detail")
        List getDetailStrings();
    
        @XBRead("/Details/*")
        List getDetails();
    }
    
    @Test
    public void xml2Hashmap() throws IOException {
        HashMap> hashmap = new HashMap>();
        for (Projection p : new XBProjector().io().fromURLAnnotation(Projection.class).getDetails()) {
            System.out.println(p.getName() + ": " + p.getDetailStrings());
            hashmap.put(p.getName(), p.getDetailStrings());
        }
    }
    }
    

    This prints out

    detail-a: [ attribute 1 of detail a ,  attribute 2 of detail a ,  attribute 3 of detail a ]
    detail-b: [ attribute 1 of detail b ,  attribute 2 of detail b ]
    

    for your example test.xml and fills a Hashmap.

提交回复
热议问题