2016-03-08 17:58 阅读 29


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

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:

Any help would be greatly appreciated, Thank you.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanhemou9834 duanhemou9834 2016-03-09 15:17

    Unfortunately, the default Go XML encoder cannot encode stuff like

    xmlns:foo="" 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="" 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="">
      <bar:elem>Hello world</bar:elem>

    use structs like this

    type Foo struct {
        XMLName xml.Name `xml:"foo"`
        BarElem BarElem
    type BarElem struct {
        XMLName xml.Name `xml:" elem"`
        Data    string   `xml:",innerxml"`

    which serializes to

      <elem xmlns="">Hello world</elem>


    点赞 评论 复制链接分享