doujiao2000 2016-03-08 17:58
浏览 29
已采纳

开始-解组XML,属性问题

Maybe somebody could give some insight here... I seem to be hitting a brick wall with the encoding/XML library.

For the life of me, I can't replicate the valid XML attributes from < gpx > Basically i'm unmarshalling the XML data from a GPS file, then marshalling it back into another file. Everything is working correctly, except the attribute tags for the root XML < gpx >

I've tried various

func (c *gpx) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {} 

type approaches to no avail.

Basically I just want the root tag < GPX > to have all the attributes assigned correctly. Why you can't do Attributes []xml.Attr xml:",attr"or something similar is beyond me.

Good XML header -> http://pastebin.com/XjEZuBa1

I can't link the bad XML header, since I'm a new member.. but the XML unmarshal/marshal process adds _ to the namespace which causes issues, among other things.

GO Playground link: http://play.golang.org/p/J7wy6306Cj

Any help would be greatly appreciated, Thank you.

  • 写回答

1条回答 默认 最新

  • duanhemou9834 2016-03-09 15:17
    关注

    Unfortunately, the default Go XML encoder cannot encode stuff like

    xmlns:foo="http://example.com/Foo-V1" foo:attr="bar"
    

    As the code shows, it chooses the name based on the URL, and you can't just define namespaces yourself. The Go encoder emits code like this which, AFAIK, is basically equivalent to the one above:

    xmlns:Foo-V1="http://example.com/Foo-V1" Foo-V1:attr="bar"
    

    The only thing that is different here is the prefix for the namespace.

    As for forward-declaration of other namespaces, I'd suggest only declaring them on elements and attributes that need them. I.e. to encode something like

    <foo xmlns:bar="http://example.com/Bar-V1">
      <bar:elem>Hello world</bar:elem>
    </foo>
    

    use structs like this

    type Foo struct {
        XMLName xml.Name `xml:"foo"`
        BarElem BarElem
    }
    
    type BarElem struct {
        XMLName xml.Name `xml:"http://example.com/Bar-V1 elem"`
        Data    string   `xml:",innerxml"`
    }
    

    which serializes to

    <foo>
      <elem xmlns="http://example.com/Bar-V1">Hello world</elem>
    </foo>
    

    Playground: http://play.golang.org/p/79bhk70yFj.

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

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab