开始-解组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.

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.