英文:
Marshal single field into two tags in golang
问题
尝试理解一种为结构化为以下形式的XML创建自定义编组器的方法:
<!-- language: lang-xml -->
<Appointment>
<Date>2004-12-22</Date>
<Time>14:00</Time>
</Appointment>
我在考虑这样的解决方案:
<!-- language: lang-go -->
type Appointment struct {
DateTime time.Time `xml:"???"`
}
问题是,我应该在"???"的位置放什么,才能将一个字段保存到两个不同的XML标签中?
英文:
Trying to understand a way to create custom marshaller for xml structured as:
<!-- language: lang-xml -->
<Appointment>
<Date>2004-12-22</Date>
<Time>14:00</Time>
</Appointment>
I'm thinking of something like:
<!-- language: lang-go -->
type Appointment struct {
DateTime time.Time `xml:"???"`
}
Question is, what would i put instead of ??? to have a single field be saved into two different xml tags?
答案1
得分: 3
复杂的编组/解组行为通常需要满足Marshal/Unmarshal接口(这对于XML、JSON和类似设置的Go类型都是如此)。
您需要使用MarshalXML()
函数满足xml.Marshaler
接口,类似以下示例:
package main
import (
"encoding/xml"
"fmt"
"time"
)
type Appointment struct {
DateTime time.Time
}
type appointmentExport struct {
XMLName struct{} `xml:"appointment"`
Date string `xml:"date"`
Time string `xml:"time"`
}
func (a *Appointment) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
n := &appointmentExport{
Date: a.DateTime.Format("2006-01-02"),
Time: a.DateTime.Format("15:04"),
}
return e.Encode(n)
}
func main() {
a := &Appointment{time.Now()}
output, _ := xml.MarshalIndent(a, "", " ")
fmt.Println(string(output))
}
// 输出:
// <appointment>
// <date>2016-04-15</date>
// <time>17:43</time>
// </appointment>
以上代码将输出XML格式的字符串。
英文:
Complex marshaling/unmarshaling behavior generally requires satisfying a Marshal/Unmarshal interface (this is of true of XML, JSON, and similarly setup types in go).
You'd need to satisfy the xml.Marshaler
interface with a MarshalXML()
function, something like the following:
package main
import (
"encoding/xml"
"fmt"
"time"
)
type Appointment struct {
DateTime time.Time
}
type appointmentExport struct {
XMLName struct{} `xml:"appointment"`
Date string `xml:"date"`
Time string `xml:"time"`
}
func (a *Appointment) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
n := &appointmentExport{
Date: a.DateTime.Format("2006-01-02"),
Time: a.DateTime.Format("15:04"),
}
return e.Encode(n)
}
func main() {
a := &Appointment{time.Now()}
output, _ := xml.MarshalIndent(a, "", " ")
fmt.Println(string(output))
}
// prints:
// <appointment>
// <date>2016-04-15</date>
// <time>17:43</time>
// </appointment>
答案2
得分: 0
快速猜测,你不能。你应该使用你的Appointment
类型实现xml.Marshaler
接口...
英文:
Quick guess, you can't. You should implement the xml.Marshaler
interface with your Appointment
type…
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论