irom
irom

Reputation: 3596

How to unmarshal Go xml?

I have xml data to unmarshal into slice of strings ["13.64.196.27/32", "13.64.198.19/32"] but getting error "undefined: Product"at the very beginning of it all. I have Product struct defined...not sure what it wants from me. See below and play.golang.org/p/Ak6bx3BLwq

func main() {
    data := `<products updated="9/1/2017">
<product name="o365">
<addresslist type="IPv4">
<address>13.64.196.27/32</address>
<address>13.64.198.19/32</address>
</addresslist>
</product>
</products>`

    type Azure struct {
        XMLName  xml.Name  `xml:"products"`
        Products []Product `xml:"product"`
    }

    type Product struct {
        XMLName xml.Name `xml:"product"`
        Name    string   `xml:"name,attr"`
        List    []List   `xml:"addresslist"`
    }

    type List struct {
        XMLName xml.Name `xml:"addresslist"`
        Type    string   `xml:"type,attr"`
        Address []string `xml:"addressList>address"`
    }

    var products Azure
    xml.Unmarshal([]byte(data), &products)
    fmt.PrintLn(products.List.Address)
}

Upvotes: 0

Views: 66

Answers (1)

Denniselite
Denniselite

Reputation: 151

Firstly you should define variables out of function implementations and secondly, you're trying to use fmt.PrintLn which doesn't exist.

I've fixed a little, hope it helps:

package main

import (
    "fmt"
    "encoding/xml"
)

type Azure struct {
    XMLName  xml.Name  `xml:"products"`
    Products []Product `xml:"product"`
}

type Product struct {
    XMLName xml.Name `xml:"product"`
    Name    string   `xml:"name,attr"`
    List    []List   `xml:"addresslist"`
}

type List struct {
    XMLName xml.Name `xml:"addresslist"`
    Type    string   `xml:"type,attr"`
    Address []string `xml:"addressList>address"`
}

func main() {
    data := `<products updated="9/1/2017">
<product name="o365">
<addresslist type="IPv4">
<address>13.64.196.27/32</address>
<address>13.64.198.19/32</address>
</addresslist>
</product>
</products>`

    var products Azure
    xml.Unmarshal([]byte(data), &products)
    fmt.Println(products)
}

Upvotes: 2

Related Questions