Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse dynamic 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?

like image 828
MZON Avatar asked Dec 20 '25 19:12

MZON


1 Answers

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

like image 138
mkopriva Avatar answered Dec 23 '25 11:12

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!