2016-04-27 40 views
1

嘗試使用golang解析一些nmap數據,但我的結構佈局不太合適。鏈接到代碼上操場:https://play.golang.org/p/kODRGiH71W正確的結構佈局來解析xml in go

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:}}}} 

回答

1

Ports包裝結構創建是不必要的層,將其刪除。您只需要對根xml元素的內容進行建模,該元素的格式爲<ports>,其內容由PortInfo進行描述/建模。不需要包裝根元素的類型。

簡單地改變

var x Ports 

var x PortInfo 

,它會工作。試試Go Playground。輸出(包裝):

{Extra:{State:closed Count:64 Reason:{Reason:conn-refused Count:64}} 
    PortProp:{Protocol:tcp Port:22 StateStuff:{State:open Reason:syn-ack}}} 
+0

謝謝@icza - 簡單修復:) – linuxfan