douxin20081125
2017-11-06 13:33 阅读 55

解组XML注释

I am trying to unmarshal XML from RRD format.

So I create my types etc, etc. which I am able to get the values from.

But there are comments in the XML in this format <!-- 2017/01/01 --> and I need to extract this date. Is there any way of accessing this in GO ?

Thanks.

Updated question:

Okay I did it works, but I want to split the comments into array.

For example I have the following XML.

<database>
<!-- Random Info. -->
<row>10101</row>
<!-- Random Info2 . -->
<row>10102</row>
</database>

So I have the following.

type Database struct {
          Comment string `xml:",comment"`   
          Row []string  `xml:"row"`
    }

Now when I print the row data I get it as an array whereas the comment is a string. I tried to make it an array but it throws an error cannot convert. panic: reflect.Set: value of type []uint8 is not assignable to type []string

Obviously, I can split the string and get what I want. But is there any quicker way of doing this when creating type?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dqxsuig64994 dqxsuig64994 2017-11-06 13:36

    Have you tried https://golang.org/pkg/encoding/xml/#Unmarshal?

    If the XML element contains comments, they are accumulated in the first struct field that has tag ",comment". The struct field may have type []byte or string. If there is no such field, the comments are discarded.

    Here's usage example: https://golang.org/src/encoding/xml/example_test.go

    type Person struct {
        XMLName   xml.Name `xml:"person"`
        ...
        Comment   string   `xml:",comment"`
    }
    
    点赞 评论 复制链接分享

相关推荐