How to distinguish XML elements with and without namespaces in Go by example?

Distinguish between XML elements with and without namespaces

In Go, you can distinguish XML elements with and without namespaces by using the xml.Name type. The xml.Name type is a struct that contains the local name and namespace URI of an XML element.

Example

package main

import (
    "encoding/xml"
    "fmt"
)

type Person struct {
    XMLName xml.Name `xml:"person"`
    Name    string   `xml:"name"`
}

type NSPerson struct {
    XMLName xml.Name `xml:"ns:person"`
    Name    string   `xml:"ns:name"`
}

func main() {
    xmlStr := `<person><name>John Doe</name></person>`
    var p Person
    if err := xml.Unmarshal([]byte(xmlStr), &p); err != nil {
        panic(err)
    }
    fmt.Printf("Person: %+v\n", p)

    nsXmlStr := `<ns:person xmlns:ns="http://example.com"><ns:name>John Doe</ns:name></ns:person>`
    var nsp NSPerson
    if err := xml.Unmarshal([]byte(nsXmlStr), &nsp); err != nil {
        panic(err)
    }
    fmt.Printf("NSPerson: %+v\n", nsp)
}

Explaination

  • we define two types, Person and NSPerson, each with an XMLName field of type xml.Name that specifies the element name.

  • In the main function, we first unmarshal an XML string without a namespace into a Person struct. Then, we unmarshal an XML string with a namespace into an NSPerson struct.

  • Note that in the NSPerson type, we use the ns: prefix to specify the namespace URI in the XML namespace declaration.

  • By using the xml.Name field in your struct, you can distinguish XML elements with and without namespaces in your Go code.