unmarshaling XML type with a choice element

510 views
Skip to first unread message

DrGo

unread,
Oct 29, 2015, 6:08:34 PM10/29/15
to golang-nuts
Hello,
Any suggestions of an easy way to use Go's builtin encoding/xml to unmarshall an XML type that has a choice element (http://www.w3schools.com/schema/el_choice.asp)
Essentially I have the following struct

type Field struct {
XMLName xml.Name `xml:"field"`
Id      string   `xml:"id,attr"`
Label   string   `xml:"label,attr"`
        ChoiceField  ??????
}

ChoiceField  can be one (and only one) of three possible elements:
1) Value with 2 attributes (including an ID) and 3 children string elements
2) Simple value: with 2 attributes (including an ID)
3) Reference value with 7 attributes (including an ID)

It is not obvious to me how to unmarshall this data. Add an innerxml and then "hand" parse it? Other ideas?

Thanks,




Giulio Iotti

unread,
Oct 30, 2015, 4:50:10 AM10/30/15
to golang-nuts
On Thursday, October 29, 2015 at 11:08:34 PM UTC+1, DrGo wrote:
ChoiceField  can be one (and only one) of three possible elements:
1) Value with 2 attributes (including an ID) and 3 children string elements
2) Simple value: with 2 attributes (including an ID)
3) Reference value with 7 attributes (including an ID)

Make a struct with all three things in it (a slice of values with two attrs, a simple value with one attr...). The unmarshaller will use them properly.

Can you make a play example with the XML to parse? It's much easier to play with. Thank you :)

-- 
Giulio Iotti 

DrGo

unread,
Oct 30, 2015, 7:55:29 PM10/30/15
to golang-nuts
Thanks Giulio,
I kind ended up doing what you said (I think). Here is what I have so far http://play.golang.org/p/A1uTpFq6Fr
I had a problem with the Value type. 
when I refer to the type in my Field type I can read the attributes but not the contents.
when I "unpack" its fields into the Field type I can read the contents but not attributes.
Not sure what I am doing wrong,

Best

Matt Harden

unread,
Oct 30, 2015, 10:40:56 PM10/30/15
to DrGo, golang-nuts

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

DrGo

unread,
Oct 31, 2015, 1:01:11 AM10/31/15
to golang-nuts, salah....@gmail.com
Thanks Matt,
Have a nice weekend,
Reply all
Reply to author
Forward
0 new messages