unmarshal xml to a struct edmx:Edmx

86 views
Skip to first unread message

RS

unread,
Oct 8, 2021, 11:09:50 AM10/8/21
to golang-nuts
I want to unmarshal an xml data to a data structure. 
Problem is the following 
This xml comes from a Odata Server and has fields "edmx:Edmx".
How should the fields of struct be named? 
I observe that the fields name of struct representing xml should be the same name as xml field name. 
Now how one can define edmx:Edmx from xml to a field that xml packet of golang can parse it?

<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx">
</edmx:Edmx>

type Metadata struct {
<???WHATFIELD NAME> xml.Name `xml:"edmx:Edmx"`
<???WHAT FIELD NAME>    string `xml:"xmlns:edmx,attr"`
Version string `xml:"Version,attr"` //this works 
....

}

Brian Candler

unread,
Oct 9, 2021, 7:57:35 AM10/9/21
to golang-nuts
Firstly, you can name the struct fields whatever you like, except it needs to start with a capital letter.  It doesn't have to match the XML element name at all.

Secondly, what you're looking at here is an XML namespace declaration.

The special attribute
binds the local namespace prefix "edmx" to the full namespace URI "http://docs.oasis-open.org/odata/ns/edmx"
and makes the local namespace prefix "edmx" available to this element and its children.

With the scope of this declaration, the element <edmx:Edmx> means "element name Edmx within namespace http://docs.oasis-open.org/odata/ns/edmx"

The namespace prefix is arbitrary and can be chosen by whoever generates the XML document.  The following XML is equivalent and needs to be parsed identically:

<womble:Edmx Version="4.0" xmlns:womble="http://docs.oasis-open.org/odata/ns/edmx">
</womble:Edmx>

You *could* pick up the xmlns attribute explicitly if you want, by matching the pseudo-namespace "xmlns" (see here):

type Metadata struct {
Version   string `xml:"Version,attr"`
Namespace string `xml:"xmlns edmx,attr"`
}

However, normally you don't want to do this, because whoever generates the XML is completely free to use whatever namespace prefix they like, e.g. "womble" instead of "edmx" as shown above.

What you should do instead is to get encoding/xml to match the actual namespace.  Here is an example:

Brian Candler

unread,
Oct 9, 2021, 8:21:59 AM10/9/21
to golang-nuts
Sorry, I forgot that you also asked about how to declare the outer <edmx:Edmx> element.

To do this, you need to add a special "XMLName" pseudo-member to your struct, which is tagged with the outer element name and namespace:

Try running this as-is, then commenting out the "XMLName" member of the struct and running it again.
Reply all
Reply to author
Forward
0 new messages