实现:

解析出示例中的 IP、type、协议、端口、时间

import (
	"github.com/beevik/etree"
	"log"
)

// 使用etree解析masscan的xml文件
func ParseMasscanXml(filePath string) {
	doc := etree.NewDocument()
	if err := doc.ReadFromFile(filePath); err != nil {
		log.Printf("解析%v失败, Error------>%v", filePath, err)
		return
	}
	// 找到数据的根节点nmaprun,nmaprun的子节点host和finished中获取IP及时间等信息
	if nmaprun := doc.SelectElement("nmaprun"); nmaprun != nil {
		// 找到finished节点,获取时间
		finishedRoot := nmaprun.SelectElement("runstats").SelectElement("finished")
		timestr := finishedRoot.SelectAttrValue("timestr", "")

		// 获取IP及端口
		for _, host := range nmaprun.SelectElements("host") {
			if address := host.SelectElement("address"); address != nil {
				ip := address.SelectAttrValue("addr", "")
				ipType := address.SelectAttrValue("addrtype", "")
			}

			for _, portRoot := range host.SelectElements("ports") {
				protocol := ""
				portId := ""
				if portInfo := portRoot.SelectElement("port"); portInfo != nil {
					protocol = portInfo.SelectAttrValue("protocol", "")
					portId = portInfo.SelectAttrValue("portid", "")
				}
 		}
		}
	}
}