dqm4675 2019-09-09 12:43
浏览 169
已采纳

解析动态XML

I understand how to unmarshal simple xml data to Go structs but can't figure out how to handle dynamic tags. Here's an example. There can be <image_3><image_4> etc

<?xml version="1.0" encoding="utf-8"?>
<products>
  <product>
    <product_id>11600</product_id>
    <date_created><![CDATA[2018-10-19 15:20:22]]></date_created>
    <price>200</price>
    <stock_status>In Stock</stock_status>
    <images>
      <image_1>1.jpg</image_1>
      <image_2>2.jpg</image_2>
   </images
   </product>
</products>

//update

type Products struct {
        XMLName xml.Name `xml:"products"`
        Text    string   `xml:",chardata"`
        Product struct {
                Text        string `xml:",chardata"`
                ProductID   string `xml:"product_id"`
                DateCreated string `xml:"date_created"`
                Price       string `xml:"price"`
                StockStatus string `xml:"stock_status"`
                Images          map[string]string `xml:"images"`
        } `xml:"product"`
} 

When I run fmt.Println(len(products.Product[0].Images)) I get 0. What I'm missing here?

  • 写回答

2条回答 默认 最新

  • douxie0824 2019-09-10 08:07
    关注

    You can implement the xml.Unmarshaler interface on a custom map type like so:

    type Images map[string]string
    
    func (i *Images) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
        *i = make(Images) // initialize the map
        for {
            tok, err := d.Token()
            if err != nil {
                if err == io.EOF {
                    return nil
                }
                return err
            }
    
            if se, ok := tok.(xml.StartElement); ok {
                tok, err = d.Token()
                if err != nil {
                    if err == io.EOF {
                        return nil
                    }
                    return err
                }
                if data, ok := tok.(xml.CharData); ok {
                    (*i)[se.Name.Local] = string(data)
                }
            }
        }
    }
    

    https://play.golang.com/p/gi9Fiv3PS8M

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问