duandaoji3992
2017-08-21 20:13
浏览 181

如何从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 20: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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题