matlabmann 2013-09-21 15:25
浏览 152
已采纳

Golang:如何用冒号解组XML属性?

Some SVG/XML files I'm working with have dashes and colons in attribute names - for example:

<g>
  <a xlink:href="http://example.com" data-bind="121">...</a>
</g>

I'm trying to figure out how to unmarshal these attributes using golang's encoding/xml package. While the dashed attributes works, the ones with the colon doesn't:

[See here for a live example]

package main

import (
    "encoding/xml"
    "fmt"
)

var data = `
<g>
    <a xlink:href="http://example.com" data-bind="121">lala</a>
</g>
`

type Anchor struct {
    DataBind  int    `xml:"data-bind,attr"`  // this works
    XlinkHref string `xml:"xlink:href,attr"` // this fails
}

type Group struct {
    A Anchor `xml:"a"`
}

func main() {
    group := Group{}
    _ = xml.Unmarshal([]byte(data), &group)

    fmt.Printf("%#v
", group.A)
}

These are seemingly legal attribute names; any idea how to extract the xlink:href one? thanks.

  • 写回答

1条回答 默认 最新

  • douqiao4450 2013-09-21 15:43
    关注

    Your example fragment is not quite correct, since it does not include an XML namespace binding for the xlink: prefix. What you probably want is:

    <g xmlns:xlink="http://www.w3.org/1999/xlink">
      <a xlink:href="http://example.com" data-bind="121">lala</a>
    </g>
    

    You can unmarshal this attribute using the namespace URL:

    XlinkHref string `xml:"http://www.w3.org/1999/xlink href,attr"`
    

    Here is an updated copy of your example program with the namespace fix.

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

报告相同问题?

悬赏问题

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