Serialize int with xml node name in go

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

Serialize int with xml node name in go

问题

我正在学习Go语言,但是在控制XML序列化方面遇到了一些问题。

我想将一个整数序列化为<number>1</number>,我尝试了以下代码:

package main

import (
	"fmt"
	"encoding/xml"
)

type number struct {
	Number int64
}

func main() {
	out, _ := xml.Marshal(number{2})
	fmt.Println(string(out))
}

但是我得到的结果是<number><Number>2</Number></number>,这是因为它被包含在结构体中导致了双重包装。如果我只序列化一个整数,我得到的结果是<int>2</int>,这个命名不正确。

有没有办法告诉序列化器不要渲染根节点,或者直接将属性放入父节点中?

英文:

I'm just in the process of learning me some go, but im having trouble controlling XML serialization

I want to serialize an int to &lt;number&gt;1&lt;/number&gt;, i have tried the following:

package main

import (
	&quot;fmt&quot;
	&quot;encoding/xml&quot;
)
type number struct {
	Number int64
}

func main() {
	out, _ := xml.Marshal(number{2})
	fmt.Println(string(out))
}

(https://play.golang.org/p/Ac-p1q3ytZ)

but I get &lt;number&gt;&lt;Number&gt;2&lt;/Number&gt;&lt;/number&gt; which is double wrapped due to the struct its in. If I just serialize an int I get &lt;int&gt;2&lt;/int&gt; which is not named correctly.

Is there a way to tell the serialize not to render the root node, or to put a property directly into the parent?

答案1

得分: 1

是的。根据xml.Marshal的文档,你可以使用标签&quot;,chardata&quot;

type number struct {
    Number int64 `xml:&quot;,chardata&quot;`
}

这将输出&lt;number&gt;2&lt;/number&gt;,可以在https://play.golang.org/p/Aoqfs04OTx中看到。

英文:

Yes. As per the documentation for xml.Marshal, you can use the tag &quot;,chardata&quot;.

type number struct {
	Number int64 `xml:&quot;,chardata&quot;`
}

This outputs &lt;number&gt;2&lt;/number&gt;, as seen at https://play.golang.org/p/Aoqfs04OTx

huangapple
  • 本文由 发表于 2017年6月20日 12:28:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/44643839.html
匿名

发表评论

匿名网友

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

确定