How to parse xml in golang with list of multiple elements values. And store them in list

I want to parse this xml and store in one data structure in golang below.

camera: LibX,LibY,...(dynamic list) display: LibP,LibQ,...(dynamic list)

 <techpackages>
    <techpackage>
        <techpackage_name> camera </techpackage_name>
        <library>LibX</library>
        <library>LibY</library>
        ....(dynamic number of libraries)
    </techpackage>
    <techpackage>
        <techpackage_name> display </techpackage_name>
        <library>LibP</library>
        <library>LibQ</library>
        ....(dynamic number of  libraries)
    </techpackage>
</techpackages>

1 answer

  • answered 2020-09-14 05:44 mkopriva

    You can unmarshal what you call "dynamic list" into a slice.

    type TechPackages struct {
        xml.Name    `xml:"techpackages"`
        TechPackage []TechPackage `xml:"techpackage"`
    }
    
    type TechPackage struct {
        TechPackageName string   `xml:"techpackage_name"`
        Library         []string `xml:"library"`
    }
    
    var pp TechPackages
    if err := xml.Unmarshal(data, &pp); err != nil {
        panic(err)
    }
    

    https://play.golang.org/p/T0shyWsBAFg