matlabmann 2013-09-21 07:25
浏览 154
已采纳

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 07: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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部