I am attempting to encode and decode an XML token in Go using the encoding/xml
package. The XML token in question has a namespace, an xmlns
attribute, and a namespace declaration for the namespace on the tag (the example here is an XMPP stream start element). It is the root element of an XMPP stream:
<?xml version="1.0" encoding="UTF-8"?>
<stream:stream
from='juliet@im.example.com'
to='im.example.com'
version='1.0'
xml:lang='en'
xmlns='jabber:client'
xmlns:stream='http://etherx.jabber.org/streams'>
(Ignore the processing instruction; I merely left that to illustrate that this is the root element)
I want to be able to read/write this token from a struct, so I fetch it as an xml.StartElement
with decoder.Token()
and manually copy all the attributes over to the struct. I then write it out with encoder.Encode(thestruct)
, but always get funny results (The xmlns is wrong, and the start tag is never stream:stream
even though the XMLName
is correct).
How should this struct be modified to be able to encode and decode to and from something like the above XML?
type stream struct {
STo string `xml:"to,attr"`
SFrom string `xml:"from,attr"`
Version string `xml:"version,attr"`
Xmlns string `xml:"xmlns,attr"`
Lang string `xml:"http://www.w3.org/XML/1998/namespace lang,attr"`
Id string `xml:"id,attr"`
XmlnsStream string `xml:"xmlns stream,attr"`
XMLName xml.Name `xml:"http://etherx.jabber.org/streams stream"`
}