XML的反序列化

huangapple go评论88阅读模式
英文:

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:

&lt;packaging&gt;
	&lt;depth measurementUnitCode=&quot;MMT&quot;&gt;1200&lt;/depth&gt;
	&lt;height measurementUnitCode=&quot;MMT&quot;&gt;1320&lt;/height&gt;
&lt;/packaging&gt;

I want it to unmarshal into the following structs:

type Packaging struct {
	Depth Depth   `xml:&quot;depth&quot;`
	Height Height `xml:&quot;height&quot;`
}

type Measurement struct {
	UnitOfMeasure `xml:&quot;measurementUnitCode,attr&quot;`
	Value float64 `xml:&quot;???????&quot;`
}

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)
}

Playground

英文:

The missing specification should be xml:&quot;,chardata&quot;.

package main

import &quot;fmt&quot;
import &quot;encoding/xml&quot;

var text = `&lt;data&gt;1.23&lt;/data&gt;`

func main() {
	data := struct {
		Value float64 `xml:&quot;,chardata&quot;`
	}{}
	xml.Unmarshal([]byte(text), &amp;data)
	fmt.Println(data)
}

<kbd>Playground</kbd>

huangapple
  • 本文由 发表于 2016年4月5日 21:31:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/36427848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定