go中的xml列表中的注释

时间:2016-06-20 14:39:34

标签: xml go

我想做点什么:

    <members>
        <!-- It's a first group -->
        <member>Whatever</member>
        ...
        <member>whatever</member>
        <!-- It's a second group -->
        <member>Whatever</member>
        ...
        <member>whatever</member>
    </members>

有没有办法用golang做这个?

1 个答案:

答案 0 :(得分:2)

你可以用两种方式做到这一点。首先,您可以将注释作为嵌入成员的更大结构的一部分,并在每次成员编组时使其成为编组注释:

type Members struct {
    XMLName xml.Name `xml:"members"`
    Members []CommentedMember
}

type CommentedMember struct {
    Member
    comment xml.Comment
}

func (cm CommentedMember) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
    if cm.comment != nil {
        err := e.EncodeToken(cm.comment)
        if err != nil {
            return err
        }
    }
    return e.Encode(cm.Member)
}

type Member struct {
    XMLName xml.Name `xml:"member"`
}

第二种方法是创建单独的Comment类型,并使Members结构包含不同的类型:

type Members2 struct {
    XMLName xml.Name `xml:"members"`
    Members []interface{}
}

type Comment string

func (cm Comment) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
    if cm != "" {
        return e.EncodeToken(xml.Comment(cm))
    }
    return nil
}

type Member struct {
    XMLName xml.Name `xml:"member"`
}

这两个都在操场上:https://play.golang.org/p/3n-xH1Zc-n