英文:
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...):
    <?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
得分: 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:"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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论