在Go中遍歷XML文檔通常使用標準庫中的encoding/xml
包。以下是一個簡單的示例代碼,演示如何遍歷一個XML文檔并打印出每個元素的名稱和屬性:
package main
import (
"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 {
Title string `xml:"title"`
Author string `xml:"author"`
Year int `xml:"year"`
Price string `xml:"price"`
}
type Bookstore struct {
Books []Book `xml:"book"`
}
var bookstore Bookstore
err := 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)
}
}
在這個示例中,我們定義了兩個結構體Book
和Bookstore
來表示XML文檔中的數據結構。然后使用xml.Unmarshal
函數將XML數據解析成對應的結構體。最后通過遍歷bookstore.Books
來打印每個書籍的信息。