Go中如何遍历XML文档


在Go中遍历XML文档通常使用标准库中的encoding/xml包。以下是一个简单的示例代码,演示如何遍历一个XML文档并打印出每个元素的名称和属性:

package mainimport ("encoding/xml""fmt""os")func main() {xmlData := []byte(`<bookstore><book category="cooking"><title lang="en">Everyday Italian</title><author>Giada De Laurentiis</author><year>2005</year><price>30.00</price></book><book category="children"><title lang="en">Harry Potter</title><author>J.K. Rowling</author><year>2005</year><price>29.99</price></book></bookstore>`)type Book struct {Titlestring `xml:"title"`Author string `xml:"author"`Year int`xml:"year"`Pricestring `xml:"price"`}type Bookstore struct {Books []Book `xml:"book"`}var bookstore Bookstoreerr := xml.Unmarshal(xmlData, &bookstore)if err != nil {fmt.Println("Error unmarshaling XML:", err)return}for _, book := range bookstore.Books {fmt.Println("Title:", book.Title)fmt.Println("Author:", book.Author)fmt.Println("Year:", book.Year)fmt.Println("Price:", book.Price)}}

在这个示例中,我们定义了两个结构体BookBookstore来表示XML文档中的数据结构。然后使用xml.Unmarshal函数将XML数据解析成对应的结构体。最后通过遍历bookstore.Books来打印每个书籍的信息。


上一篇:python中utils包不能导入怎么解决

下一篇:c++多个变量赋值要注意哪些事项


go
Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器