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. Thexml.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
andNSPerson
, each with anXMLName
field of typexml.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.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go