Golang XML attribute and value

The tag xml:",chardata" will select the current element's character data, as you want, but only for the first field with that tag. This is why you got the results you observed.

For the given XML, I would suggest decoding into the following types:

type HostProperties struct {
    XMLName xml.Name `xml:"HostProperties"`
    Info    []Tag    `xml:"tag"`
}

type Tag struct {
    Name  string `xml:"name,attr"`
    Value string `xml:",chardata"`
}

It won't automatically split the various named tags into separate fields for you though: you will need to do that after processing the XML.


I don't think you can make the XML parsing work like that. Here is the best I could come up with (run it on the playground)

var data = `<HostProperties>
<tag name="HOST_END">Thu Feb 20 12:38:24 2014</tag>
<tag name="patch-summary-total-cves">4</tag>
<tag name="cpe-1">cpe:/a:openbsd:openssh:5.6 -&gt; OpenBSD OpenSSH 5.6</tag>
<tag name="cpe-0">cpe:/o:vmware:esx_server</tag>
<tag name="system-type">hypervisor</tag>
<tag name="operating-system">VMware ESXi</tag>
<tag name="mac-address">00:00:00:00:00:00</tag>
<tag name="traceroute-hop-0">172.28.28.29</tag>
<tag name="host-ip">172.28.28.29</tag>
<tag name="host-fqdn">foobar.com</tag>
<tag name="HOST_START">Thu Feb 20 12:30:14 2014</tag>
</HostProperties>`

type HostProperties struct {
    XMLName xml.Name `xml:"HostProperties"`
    Tags    []Tag    `xml:"tag"`
}

type Tag struct {
    Key   string `xml:"name,attr"`
    Value string `xml:",chardata"`
}

func main() {
    v := new(HostProperties)
    err := xml.Unmarshal([]byte(data), v)
    if err != nil {
        fmt.Printf("error: %v", err)
        return
    }
    fmt.Printf("v = %#v\n", v)

}

If you really want that InfoList structure you'll have to run through the Tags and fill it in. I'd probably just stick it in a map[string]string though like this

tags := make(map[string]string)
for _, tag := range v.Tags {
    tags[tag.Key] = tag.Value
}
fmt.Printf("map = %#v\n", tags)

Tags:

Xml

Go