简体   繁体   中英

decoding XML in golang

I'm trying to decode the following xml. For some reasons I can't decode the Id

package main

import (
    "encoding/xml"
    "fmt"
)

var data = `
<g xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ad="http://www.myschema.com/schema/ad/v1">
    <a xlink:href="http://example.com" data-bind="121">lala</a>
    <ad:ad id="1060469006">
</g>
`

type Anchor struct {
    DataBind  int    `xml:"data-bind,attr"`  
    XlinkHref string `xml:"http://www.w3.org/1999/xlink href,attr"`
    Id int  `xml:"http://www.myschema.com/schema/ad/v1 id,attr"` 
}

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

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

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

Play

The structs you are decoding into are looking for a ad:id attribute on the <a> element in the XML. There are two reasons this isn't working:

  1. the id attribute is on a different element.
  2. the id attribute is not in the http://www.myschema.com/schema/ad/v1 namespace. Attributes without a namespace prefix do not inherit the namespace of their element: instead they are part of the blank namespace.

So to fix this, first you need another field in Group with the tag xml:"http://www.myschema.com/schema/ad/v1 ad" , and the struct definition for that field needs its own field with the tag xml:"id,attr" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM