2016-04-27 16 views
1

Versuchen, einige nmap Daten mit Golang zu analysieren, aber das Layout meiner Strukturen funktioniert nicht ganz. Link zum Code auf Spielplatz: https://play.golang.org/p/kODRGiH71WKorrektes Layout von Strukturen zum Parsen von 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:}}}} 

Antwort

1

Die Schicht, die die Ports Wrapper-Struktur ist nicht notwendig, schafft, legen Sie es. Sie müssen nur den Inhalt des Root-XML-Elements modellieren, das <ports> ist und dessen Inhalt durch beschrieben/modelliert wird. Es ist kein Typ erforderlich, der das Wurzelelement umschließt.

einfach zu ändern

var x Ports 

zu

var x PortInfo 

Und es wird funktionieren. Versuchen Sie es auf der Go Playground. Ausgabe (eingewickelt):

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

Dank @icza - einfache Lösung :) – linuxfan