douweibiao8471 2014-11-26 22:48
浏览 198
已采纳

在golang中使用XMLNS声明对XML根令牌进行编码/解码

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"`
}
  • 写回答

1条回答 默认 最新

  • duanpang1987 2014-11-27 06:49
    关注

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站