尝试使用golang解析一些nmap数据,但我的结构布局并不是很有效。链接到操场上的代码:https://play.golang.org/p/kODRGiH71W
package main
import (
"encoding/xml"
"fmt"
)
type Extrareasons struct {
Reason string `xml:"reason,attr"`
Count uint32 `xml:"count,attr"`
}
type Extraports struct {
State string `xml:"state,attr"`
Count uint32 `xml:"count,attr"`
Reason Extrareasons `xml:"extrareasons"`
}
type StateProps struct {
State string `xml:"state,attr"`
Reason string `xml:"reason,attr"`
}
type PortProps struct {
Protocol string `xml:"protocol,attr"`
Port uint32 `xml:"portid,attr"`
StateStuff StateProps `xml:"state"`
}
type PortInfo struct {
Extra Extraports `xml:"extraports"`
PortProp PortProps `xml:"port"`
}
type Ports struct {
Port PortInfo `xml:"ports"`
}
func main() {
xmlString := `<ports>
<extraports state="closed" count="64">
<extrareasons reason="conn-refused" count="64" />
</extraports>
<port protocol="tcp" portid="22">
<state state="open" reason="syn-ack" reason_ttl="0" />
<service name="ssh" method="table" conf="3" />
</port>
</ports>`
var x Ports
if err := xml.Unmarshal([]byte(xmlString), &x); err == nil {
fmt.Printf("%+v\n", x)
} else {
fmt.Println("err:", err)
}
}
$ go run test.go
{Port:{Extra:{State: Count:0 Reason:{Reason: Count:0}} PortProp:{Protocol: Port:0 StateStuff:{State: Reason:}}}}
答案 0 :(得分:1)
Ports
包装器结构创建的层是不必要的,删除它。您只需要对根{x}元素的内容进行建模,其内容由<ports>
描述/建模。不需要包含根元素的类型。
只需更改
PortInfo
到
var x Ports
它会起作用。在Go Playground上试一试。输出(包裹):
var x PortInfo