Go语言encoding/xml包支持类型安全的XML解析与序列化,通过struct tag映射字段,支持属性(attr)、文本(chardata)、切片自动收集、命名空间及Marshal/Unmarshal操作。

Go 语言的 encoding/xml 包提供了简洁、高效且类型安全的 XML 解析与序列化能力。它不依赖外部库,原生支持结构体标签映射,适合处理配置文件、API 响应(如 RSS、SOAP)、简单数据交换等场景。
解析 XML 的核心是将 XML 元素与 Go 结构体字段通过 xml struct tag 映射。标签语法为 xml:"name,attr|chardata|omitempty|any",常用选项包括:
Name → <name></name>),也可显式指定:xml:"user_name"
attr:如 ID int `xml:"id,attr"` 对应 <user id="123"></user>
chardata:如 Content string `xml:",chardata"` 捕获 <title>Hello</title> 中的 Hello
omitempty:序列化时忽略零值字段(不影响解析)使用 xml.Unmarshal 将字节切片或 io.Reader 解析为结构体。注意错误检查不可省略:
data := []byte(`<user id="1001"><name>Alice</name><age>30</age></user>`)
var u User
err := xml.Unmarshal(data, &u)
if err != nil {
log.Fatal(err)
}
// u.ID == 1001, u.Name == "Alice", u.Age == 30
从文件读取时可直接传入 *os.File 或其他 io.Reader(如 bytes.NewReader(data)、http.Response.Body)。
立即学习“go语言免费学习笔记(深入)”;
XML 中常见列表(如多个 <item></item>)可用切片接收:
type Feed struct {
XMLName xml.Name `xml:"rss"`
Channel Channel `xml:"channel"`
}
type Channel struct {
Title string `xml:"title"`
Items []Item `xml:"item"` // 自动收集所有 <item> 节点
}
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
PubDate string `xml:"pubDate"`
}
命名空间(如 xmlns:dc="http://purl.org/dc/elements/1.1/")需在 tag 中完整写出前缀,例如:Creator string `xml:"dc:creator"`。若不确定命名空间,可用 xml:",any" 捕获未知子元素(慎用,会丢失结构)。
用 xml.Marshal 或 xml.MarshalIndent(带缩进)将结构体转为 XML 字节流:
u := User{ID: 999, Name: "Bob", Age: 25}
output, err := xml.MarshalIndent(u, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(output))
// 输出:
// <user id="999">
// <name>Bob</name>
// <age>25</age>
// </user>
注意:根结构体字段若未设置 xml:"name",默认以结构体名小写作为根元素名;若想自定义根名,可嵌套一层或使用匿名字段 + 显式 tag。
基本上就这些。Golang 的 XML 支持不复杂但容易忽略 tag 细节,尤其 attr 和 chardata 的位置、切片自动收集机制,以及命名空间写法。实际用时建议先打印原始 XML,再对照结构体标签逐步调试。
以上就是如何使用Golang encoding/xml解析XML数据_Golang XML编码与解析示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号