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.

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

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行