Avoid XML parsing errors if empty
Consider these 2 XML documents
<a> <b nil="true"></b> </a> and
<a> <b type="integer">1</b> </a> How can I correctly untangle this XML in Go in the structure field b type int without creating the error strconv.ParseInt: parsing "": invalid syntax in the first case?
omitempty doesn't seem to work in this case.
Example: http://play.golang.org/p/fbhVJ4zUbl
The omitempty symbol is simply respected with the marshal, not with Unmarshal.
Reject errors if int is not an actual int.
Instead, change B to a string. Then convert B to int with the strconv package. If this is an error, set the value to 0.
Try this snippet: http://play.golang.org/p/1zqmlmIQDB
You can use the package "github.com/guregu/null". It helps:
package main import ( "fmt" "encoding/xml" "github.com/guregu/null" ) type Items struct{ It []Item `xml:"Item"` } type Item struct { DealNo string ItemNo null.Int Name string Price null.Float Quantity null.Float Place string } func main(){ data := ` <Items> <Item> <DealNo/> <ItemNo>32435</ItemNo> <Name>dsffdf</Name> <Price>135.12</Price> <Quantity></Quantity> <Place>dsffs</Place> </Item> <Item> <DealNo/> <ItemNo></ItemNo> <Name>dsfsfs</Name> <Price></Price> <Quantity>1.5</Quantity> <Place>sfsfsfs</Place> </Item> </Items>` var xmlMsg Items if err := xml.Unmarshal([]byte(data), &xmlMsg); err != nil { fmt.Println("Error: cannot unmarshal xml from web ", err) } else { fmt.Println("XML: ", xmlMsg) } }