登录
首页 >  Golang >  Go问答

XML 解组属性和内部值

来源:stackoverflow

时间:2024-04-21 17:18:25 428浏览 收藏

大家好,今天本人给大家带来文章《XML 解组属性和内部值》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

当尝试解析某些 xml 时,如下面的示例所示。

如何引用和解析owner的属性“id”?

import (
    "encoding/xml"
    "fmt"
)

var Sample = `                                                                                                                                                                      
                                                                                                                                                                                     
                                                                                                                                                                              
    John Smith                                                                                                                                                       
    Box                                                                                                                                                                        
    Kitchen                                                                                                                                                            
                                                                                                                                                                                     
`

type Item struct {
    XMLName  xml.Name `xml:"item"`
    Id       int      `xml:"id,attr"`
    Owner    string   `xml:"owner"`
    OwnerId  int      `xml:"owner,id,attr"`
    Name     string   `xml:"name"`
    Location string   `xml:"location"`
}

type Items struct {
    XMLName xml.Name `xml:"items"`
    Items   []Item   `xml:"item"`
}

func main() {
    items := Items{}
    data := []byte(Sample)
    xml.Unmarshal(data, &items)
    fmt.Println("items: ", items)
}

正确答案


引用所有者的属性“id”:items.items[0].owner.id

fmt.Println("Owner Id: ", items.Items[0].Owner.Id)

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《XML 解组属性和内部值》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>