Unmarshaling XML in Go with conflicting element names

I have the following XML, externally defined and outside of my organization management:

<foo>
  <bar>
    <zip>zip</zip>
  </bar>
  <bar>
    <zap>zap</zap>
  </bar>
</foo>

I use these structures:

type Foo struct {
    XMLName xml.Name `xml:"foo"`
    Bar1    Bar1
    Bar2    Bar2
}

type Bar1 struct {
    XMLName xml.Name `xml:"bar"`
    Zip     string   `xml:"zip"`
}

type Bar2 struct {
    XMLName xml.Name `xml:"bar"`
    Zap     string   `xml:"zap"`
}

Because of the controversial name "bar", nothing becomes messy. How can I fill the structures Bar1 and Bar2?

This is what I have: https://play.golang.org/p/D2IRLojcTB

As a result, I want: https://play.golang.org/p/Ytrbzzy9Ok

In the second, I updated the second "bar" as "bar1", and it all works. I would prefer a cleaner solution that modifies the incoming XML.

+4
source share
1 answer

encoding/xml , , , Foo , <bar>, . , xml.Unmarshal :

main.Foo "Bar1" " " Bar2 " " "

, :

1. Bar

:

type Foo struct {
    XMLName xml.Name `xml:"foo"`
    Bars    []Bar    `xml:"bar"`
}

type Bar struct {
    Zip string `xml:"zip"`
    Zap string `xml:"zap"`
}

, <bar>. , <zip> <zap>, , .

: https://play.golang.org/p/kguPCYmKX0

2.

<bar> , , . , :

type Foo struct {
    XMLName xml.Name `xml:"foo"`
    Zip     string   `xml:"bar>zip"`
    Zap     string   `xml:"bar>zap"`
}

<bar> Foo. , , ,

<foo>
  <bar>
    <zip>zip</zip>
    <zap>zap</zap>
  </bar>
</foo>

, .

: https://play.golang.org/p/fAE_HSrv4y

+9

All Articles