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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?