Answer the question
In order to leave comments, you need to log in
How can fields be handled in a struct?
Hey! Can you please tell me how to process the fields in the structure?
For example, there is an `xml` file in which some fields are crooked, for example, there are many spaces that you want to trim
<Document>
<Price>100.00</Price>
</Document>
<Document>
<Price> 500.00</Price>
</Document>
type Feed struct {
Products []Product `xml:"Document" json:"products""`
}
type Product struct {
Price string `xml:"Price" json:"price"`
}
func main() {
xmlFile, err := os.Open("feed.xml")
defer xmlFile.Close()
if err != nil {
log.Fatal(err)
}
byteValue, _ := ioutil.ReadAll(xmlFile)
var feed Feed
xml.Unmarshal(byteValue, &feed)
b, err := json.Marshal(feed)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(b))
}
{
"products": [
{ "price": "100.00" },
{ "price": " 500.00" }
]
}
{
"products": [
{ "price": "100.00" },
{ "price": "500.00" }
]
}
Answer the question
In order to leave comments, you need to log in
Implement custom UnmarshalXML
func (p *Product) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
v := struct {
Price string `xml:"Price"`
}{}
d.DecodeElement(&v, &start)
p.Price = strings.Trim(v.Price, " ")
return nil
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question