英文:
Unmarshalling XML
问题
我有以下要解组的XML:
<packaging>
<depth measurementUnitCode="MMT">1200</depth>
<height measurementUnitCode="MMT">1320</height>
</packaging>
我希望将其解组为以下结构体:
type Packaging struct {
Depth Depth `xml:"depth"`
Height Height `xml:"height"`
}
type Measurement struct {
UnitOfMeasure `xml:"measurementUnitCode,attr"`
Value float64 `xml:"???????"`
}
UnitOfMeasure
是没问题的,但我不知道如何设置实际的Value
。我该怎么做?
英文:
I have the following XML which I want to unmarshal:
<packaging>
<depth measurementUnitCode="MMT">1200</depth>
<height measurementUnitCode="MMT">1320</height>
</packaging>
I want it to unmarshal into the following structs:
type Packaging struct {
Depth Depth `xml:"depth"`
Height Height `xml:"height"`
}
type Measurement struct {
UnitOfMeasure `xml:"measurementUnitCode,attr"`
Value float64 `xml:"???????"`
}
The UnitOfMeasure
is fine, but I can't figure how to get the actual Value
set. How do I do that?
答案1
得分: 2
缺失的规范应该是 xml:",chardata"
。
package main
import "fmt"
import "encoding/xml"
var text = `<data>1.23</data>`
func main() {
data := struct {
Value float64 `xml:",chardata"`
}{}
xml.Unmarshal([]byte(text), &data)
fmt.Println(data)
}
英文:
The missing specification should be xml:",chardata"
.
package main
import "fmt"
import "encoding/xml"
var text = `<data>1.23</data>`
func main() {
data := struct {
Value float64 `xml:",chardata"`
}{}
xml.Unmarshal([]byte(text), &data)
fmt.Println(data)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论