duandaoji3992 2017-08-21 20: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 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

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?