Search code examples
xmlgoxml-namespaces

How to unmarshal xml element with colon


As the code blow, I could not unmarshal xml element with colon in Go.

https://play.golang.org/p/zMm5IQSfS01

package main

import (
    "fmt"
    "encoding/xml"
)

type Obj struct {
    XMLName xml.Name `xml:"book"`
    AbcName string   `xml:"abc:name"`
}

func main() {
    a := []byte(`<book><abc:name>text</abc:name></book>`)
    obj := &Obj{}
    if err := xml.Unmarshal(a, obj); err != nil {
        panic(err)
    }
    fmt.Printf("%#v\n", obj)
}

The code outputs:

&main.Obj{XMLName:xml.Name{Space:"", Local:"book"}, AbcName:""}

Is it possible to unmarshal xml element with colon in Golang? If yes, how?


Solution

  • xml.Unmarshal

    If the XMLName field has an associated tag of the form "name" or "namespace-URL name", the XML element must have the given name (and, optionally, name space) or else Unmarshal returns an error.

    type Obj struct {
        XMLName xml.Name `xml:"book"`
        AbcName string   `xml:"abc name"`
        DefName string   `xml:"def name"`
    }
    
    func main() {
        a := []byte(`<book><abc:name>text</abc:name><def:name>some other text</def:name></book>`)
        obj := &Obj{}
        if err := xml.Unmarshal(a, obj); err != nil {
            panic(err)
        }
        fmt.Printf("%#v\n", obj)
    }