如何解组Go xml?

时间:2017-09-07 20:11:23

标签: xml go unmarshalling

我有xml数据要解组成一串字符串[" 13.64.196.27/32"," 13.64.198.19/32"]但是收到错误" undefined:产品"在它的最开始。我定义了Product struct ...不确定它对我有什么要求。见下文和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)
}

1 个答案:

答案 0 :(得分:2)

首先,您应该从功能实现中定义变量;其次,您尝试使用不存在的fmt.PrintLn

我已经修了一下,希望有所帮助:

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