关闭
duandaoji3992 2017-08-21 12:13
浏览 197
已采纳

如何从go中的XML元素(结构标签)获取文本?

The following XML has an exemple of an element that has nested fields (title, author etc) and a text (Blah Blah...):

    <?xml version="1.0" encoding="UTF-8"?>
    <book category="cooking">
      <title lang="en">Everyday Italian</title>
      <author>Giada De Laurentiis</author>
      <year>2005</year>
      <price>30.00</price>
      Blah Blah Blah Bleh Blah
    </book>

I've coded this structure to decode this XML but I don't know which structure tag I should use in this case. I search in the docs but i have found nothing.

    type Book struct{
       t string `xml:"book>title"`
       p string `xml:"book>price"`
       y string `xml:"book>year"`
       a string `xml:"book>author"`
       blah string ???????
    }
  • 写回答

1条回答 默认 最新

  • doushadu0901 2017-08-21 12:23
    关注

    Per the documentation:

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

    So, you can decode it with a struct as such:

    type Book struct {
        Title   string   `xml:"title"`
        Price   string   `xml:"price"`
        Year    string   `xml:"year"`
        Author  string   `xml:"author"`
        Body    string   `xml:",chardata"`
    }
    

    (Note that fields you're unmarshaling into must be exported, i.e., must start with an uppercase letter, or they cannot be unmarshaled into.)

    You can see an example here: https://play.golang.org/p/OlwSqnHsT7

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部