Try to unmarshal a xml file like:
<Element>
<![CDATA[hello]]>
<image>some_url_here</image>
<![CDATA[world]]>
mixed content here
</Element>
there are different types of data inside the Element tag, how can I unmashal this xml into a struct like:
type XMLElement struct {
XMLName xml.Name `xml:"Element"`
CDatas []string `....`
Image string `...`
PlainText string `...`
}
or any other struct this xml could be unmarshalled in.
This solution is not so good, because xmlquery mades CDATA
element as TEXT node type, but I considered it is easy and simple, it using XPath
query.
package main
import (
"fmt"
"strings"
"github.com/antchfx/xmlquery"
)
func main() {
s := `<?xml version="1.0" encoding="UTF-8"?><Element>
<![CDATA[hello]]>
<image>some_url_here</image>
<![CDATA[world]]>
</Element>
`
doc, err := xmlquery.Parse(strings.NewReader(s))
if err != nil {
panic(err)
}
elem := xmlquery.FindOne(doc, "//Element")
for n := elem.FirstChild; n != nil; n = n.NextSibling {
if n.Data == "image" {
fmt.Printf("image: %s
", n.InnerText())
} else if n.Type == xmlquery.TextNode {
if len(strings.TrimSpace(n.InnerText())) == 0 {
// skip it because its' empty node
} else {
fmt.Printf("cdata: %s
", n.InnerText())
}
}
}
// or using query expression
image := xmlquery.FindOne(doc, "//image")
fmt.Printf("image: %s
", image.InnerText())
}