如果字段为空,则避免XML整数解析错误

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

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

You can use "github.com/guregu/null" package. 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)
        }
}