Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid XML integer parse errors if field empty

Tags:

go

Consider these 2 XML documents

<a>
  <b nil="true"></b>
</a>

and

<a>
  <b type="integer">1</b>
</a>

How can I unmarshal this XML properly in Go to a b struct field of type int, without producing a strconv.ParseInt: parsing "": invalid syntax error in the first case?

omitempty doesn't seem to work in this case.

Example: http://play.golang.org/p/fbhVJ4zUbl

like image 309
Era Avatar asked Jul 10 '13 13:07

Era


1 Answers

The omitempty tag is just respected with Marshal, not Unmarshal.

Unmarshal errors if the int value is not an actual int.

Instead, change B to a string. Then, convert B to an int with the strconv package. If it errors, set it to 0.

Try this snippet: http://play.golang.org/p/1zqmlmIQDB

like image 195
matthewbauer Avatar answered Oct 16 '22 17:10

matthewbauer