duandaoji3992 2017-08-21 20:13
浏览 196
已采纳

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

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

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容