简体   繁体   中英

Encoding/decoding XML root token with XMLNS declaration in golang

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"`
}

You get correct results, because:

<stream:stream
      xmlns:stream='http://etherx.jabber.org/streams' />

is the same as

<stream xmlns='http://etherx.jabber.org/streams' />

Jabber's XMLs are pretty sophisticated, so if you wan't to end up with correct XMPP XMLs, you probably need to write your own encoder.

By the way, if you look at Golang XMPP implementations you'll see they all use own encoding (and, often, decoding).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM