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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器