如何在Go中从XML元素(使用结构体标签)中获取文本?

huangapple go评论93阅读模式
英文:

How to get the text from an XML element in go (structs tags)?

问题

以下是一个具有嵌套字段(title、author等)和文本(Blah Blah...)的元素示例的XML:

    <?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>

我已经编写了用于解码此XML的结构,但我不知道在这种情况下应该使用哪个结构标签。我在文档中搜索了一下,但没有找到相关内容。

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 ???????
}

英文:

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

    &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    &lt;book category=&quot;cooking&quot;&gt;
      &lt;title lang=&quot;en&quot;&gt;Everyday Italian&lt;/title&gt;
      &lt;author&gt;Giada De Laurentiis&lt;/author&gt;
      &lt;year&gt;2005&lt;/year&gt;
      &lt;price&gt;30.00&lt;/price&gt;
      Blah Blah Blah Bleh Blah
    &lt;/book&gt;

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:&quot;book&gt;title&quot;`
       p string `xml:&quot;book&gt;price&quot;`
       y string `xml:&quot;book&gt;year&quot;`
       a string `xml:&quot;book&gt;author&quot;`
       blah string ???????
    }

答案1

得分: 5

根据文档

> 如果XML元素包含字符数据,则该数据将累积在具有标签",chardata"的第一个结构字段中。结构字段可以是[]byte或string类型。如果没有这样的字段,则字符数据将被丢弃。

因此,您可以使用以下结构体解码它:

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

(请注意,您要解组的字段必须是公开的,即必须以大写字母开头,否则无法解组。)

您可以在这里查看一个示例:https://play.golang.org/p/OlwSqnHsT7

英文:

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:&quot;title&quot;`
	Price   string   `xml:&quot;price&quot;`
	Year    string   `xml:&quot;year&quot;`
	Author  string   `xml:&quot;author&quot;`
	Body    string   `xml:&quot;,chardata&quot;`
}

(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

huangapple
  • 本文由 发表于 2017年8月22日 04:13:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/45804868.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定