英文:
Avoid XML integer parse errors if field empty
问题
考虑这两个XML文档
<a>
<b nil="true"></b>
</a>
和
<a>
<b type="integer">1</b>
</a>
如何在Go中正确地将此XML解组为类型为int的b
结构字段,而不会在第一种情况下产生strconv.ParseInt: parsing "": invalid syntax
错误?
在这种情况下,omitempty
似乎不起作用。
示例:http://play.golang.org/p/fbhVJ4zUbl
英文:
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
答案1
得分: 1
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
英文:
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
答案2
得分: 0
你可以使用"github.com/guregu/null"包。它有助于:
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)
}
}
英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论