我似乎无法弄清楚为什么这不工作
type HostProperties struct { XMLName xml.Name `xml:HostProperties"` Info []InfoList `xml:"tag"` } type InfoList struct { HostEnd string `xml:",chardata"` PatchSummary string `xml:",chardata"` CPE1 string `xml:",chardata"` CPE0 string `xml:",chardata"` SystemType string `xml:",chardata"` OperatingSystem string `xml:",chardata"` MacAddress string `xml:",chardata"` Traceroute string `xml:",chardata"` IP string `xml:",chardata"` FQDN string `xml:",chardata"` HostStart string `xml:",chardata"` } <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 -> 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>
结果
{HostEnd:172.28.28.29 PatchSummary: CPE1: CPE0: SystemType: OperatingSystem: MacAddress: Traceroute: IP: FQDN: HostStart:}
它创建一堆新的片,只有第一个元素填充,甚至是错误的元素.它没有填写其他变量.文件的其余部分似乎解析不错,只是无法弄清楚这部分.
我不认为你可以使XML解析工作.这是我可以想出来的最好的(
run it on the playground)
原文链接:https://www.f2er.com/go/186785.htmlvar 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 -> 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) }
如果你真的想要这个InfoList结构,你必须运行这个标签并填写它.我可能只是把它粘贴在一个地图[string]字符串,虽然像这样
tags := make(map[string]string) for _,tag := range v.Tags { tags[tag.Key] = tag.Value } fmt.Printf("map = %#v\n",tags)