英文:
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 <number>1</number>
, i have tried the following:
package main
import (
"fmt"
"encoding/xml"
)
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 <number><Number>2</Number></number>
which is double wrapped due to the struct its in. If I just serialize an int I get <int>2</int>
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
的文档,你可以使用标签",chardata"
。
type number struct {
Number int64 `xml:",chardata"`
}
这将输出<number>2</number>
,可以在https://play.golang.org/p/Aoqfs04OTx中看到。
英文:
Yes. As per the documentation for xml.Marshal
, you can use the tag ",chardata"
.
type number struct {
Number int64 `xml:",chardata"`
}
This outputs <number>2</number>
, as seen at https://play.golang.org/p/Aoqfs04OTx
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论