dsj2014 2016-04-27 23:12
浏览 65
已采纳

正确的结构布局以解析Go中的xml

Trying to parse some nmap data with golang, but the layout of my structs isn't quite working. Link to code on playground: 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
", 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:}}}}
  • 写回答

1条回答 默认 最新

  • dttl3933 2016-04-27 23:18
    关注

    The layer that the Ports wrapper struct creates is unnecessary, drop it. You only need to model the contents of the root xml element which is <ports> and its content is described / modeled by PortInfo. There is no need for a type that wraps the root element.

    Simply change

    var x Ports
    

    to

    var x PortInfo 
    

    And it will work. Try it on the Go Playground. Output (wrapped):

    {Extra:{State:closed Count:64 Reason:{Reason:conn-refused Count:64}}
        PortProp:{Protocol:tcp Port:22 StateStuff:{State:open Reason:syn-ack}}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器