dpizd08264 2017-09-07 20:11
浏览 27

如何解组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)
}
  • 写回答

1条回答 默认 最新

  • dousiyou1058 2017-09-07 20:31
    关注

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大