I have the following code:
package main
import (
"encoding/xml"
"fmt"
)
func main() {
xr := &xmlResponse{}
if err := xml.Unmarshal([]byte(x), &xr); err != nil {
panic(err)
}
fmt.Printf("%+v", xr)
}
type xmlResponse struct {
//Title string `xml:"title,omitempty"`
Title struct {
BoldWords []struct {
Bold string `xml:",chardata"`
} `xml:"bold,omitempty"`
Title string `xml:",chardata" `
} `xml:"title,omitempty"`
}
var x = `<?xml version="1.0" encoding="utf-8"?>
<mytag version="1.0">
<title><bold>Go</bold> is a programming language. I repeat: <bold>Go</bold> is a programming language.</title>
</mytag>`
This outputs:
&{Title:{BoldWords:[{Bold:Go} {Bold:Go}] Title: is a programming language. I repeat: is a programming language.}}
How do I get:
<bold>Go</bold> is a programming language. I repeat: <bold>Go</bold> is a programming language.
In other words, I need not only the tags but also keep them in the proper place and not just a slice of bolded items. Trying to get it just as a string (e.g. uncommenting the first "Title" in xmlResponse struct) leaves out the bolded items entirely.
From the Docs
If the XML element contains character data, that data is
accumulated in the first struct field that has tag ",chardata". The struct field may have type []byte or string. If there is no such field, the character data is discarded.
This is actually not what you want, what you're looking for is:
If the struct has a field of type []byte or string with tag
",innerxml", Unmarshal accumulates the raw XML nested inside the
element in that field. The rest of the rules still apply.
So, use innerxml
instead of chardata
.
package main
import (
"encoding/xml"
"fmt"
)
func main() {
xr := &xmlResponse{}
if err := xml.Unmarshal([]byte(x), &xr); err != nil {
panic(err)
}
fmt.Printf("%+v", xr)
}
type xmlResponse struct {
//Title string `xml:"title,omitempty"`
Title struct {
Title string `xml:",innerxml" `
} `xml:"title,omitempty"`
}
var x = `<?xml version="1.0" encoding="utf-8"?>
<mytag version="1.0">
<title><bold>Go</bold> is a programming language. I repeat: <bold>Go</bold> is a programming language.</title>
</mytag>`
Outputs:
&{Title:{Title:<bold>Go</bold> is a programming language. I repeat: <bold>Go</bold> is a programming language.}}