golang中的多种类型的解码器 [英] Multiple-types decoder in golang
问题描述
我有一个XML文档。某些字段具有自定义格式。示例:
< document>
< title> hello world< / title>
<行>
第1行
第2行
第3行
< / lines>
< / document>
我想将它导入到如下结构中:
类型结构{
标题字符串`xml:title`
Lines [] string`xml:lines`
}
有什么方法可以实现自定义解码器,它会将行字符串分成几行( [line 1,line 2,line 3]
)?
一个字符串类型并在xml导入后进行分割,但它似乎不是非常优雅的解决方案。有没有什么办法可以定义自定义解码器来进行行分割并将其与xml解码器相结合?解决方案
您可以通过定义一个符合 xml.Unmarshaler
接口的新类型。因此,不要使用 Lines
a []字符串
,用适当的 UnmarshalXML声明新类型
方法。例如:
type Lines [] string
func(l * Lines)UnmarshalXML(d * xml.Decoder,start xml.StartElement)error {
var content string
if err:= d.DecodeElement(& content,& start); err!= nil {
return err
}
* l = strings.Split(content,\\\
)
return nil
}
你可以在这里看到一个完整的例子: http://play.golang.org/p/3SBu3bOGjR
如果您也想支持此类型的编码,您可以实现 MarshalXML
方法(构建您想要的字符串内容并将其传递给编码器)。
I have an XML document. Some fields have custom format. Example:
<document>
<title>hello world</title>
<lines>
line 1
line 2
line 3
</lines>
</document>
I want to import it into structure like:
type Document struct {
Title string `xml:"title"`
Lines []string `xml:"lines"`
}
Is there some way how to implement custom decoder, which will split lines string into array of lines (["line 1", "line 2", "line 3"]
)?
Its possible to make Lines field a string type and make split after xml import, but it doesn't seems to be very elegant solution. Is there any way i can define custom decoder for line spliting and combine it with xml decoder?
You can achieve this by defining a new type that conforms to the xml.Unmarshaler
interface. So rather than making Lines
a []string
, declare a new type with an appropriate UnmarshalXML
method. For instance:
type Lines []string
func (l *Lines) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
var content string
if err := d.DecodeElement(&content, &start); err != nil {
return err
}
*l = strings.Split(content, "\n")
return nil
}
You can see a full example here: http://play.golang.org/p/3SBu3bOGjR
If you want to support encoding this type too, you can implement the MarshalXML
method in a similar fashion (construct the string content you want and pass that to the encoder).
这篇关于golang中的多种类型的解码器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!