You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Golang:如何获取XML根元素动态属性及根元素名称

提取XML根元素的属性与元素名

目标XML示例

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.opentravel.org/OTA/2003/05">
    <soap:Header/>
    <soap:Body>
        <contents>
            <article>
                <category>Server</category>
                <title>Connect to Oracle Server using Golang and Go-OCI8 on Ubuntu</title>
                <url>/go-oci8-oracle-linux/</url>
            </article>
            <article>
                <category>Server</category>
                <title>Easy Setup OpenVPN Using Docker DockVPN</title>
                <url>/easy-setup-openvpn-docker/</url>
            </article>
            <article info="popular article">
                <category>Server</category>
                <title>Setup Ghost v0.11-LTS, Ubuntu, Nginx, Custom Domain, and SSL</title>
                <url>/ghost-v011-lts-ubuntu-nginx-custom-domain-ssl/</url>
            </article>
        </contents>
    </soap:Body>
</soap:Envelope>

需求

  1. 提取根元素所有属性,返回为map[string]string(属性键值动态获取,无固定限制)
  2. 提取根元素的完整名称字符串(如soap:Envelope)

Golang实现代码

package main

import (
	"encoding/xml"
	"fmt"
)

func main() {
	xmlData := `
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns="http://www.opentravel.org/OTA/2003/05">
    <soap:Header/>
    <soap:Body>
        <contents>
            <article>
                <category>Server</category>
                <title>Connect to Oracle Server using Golang and Go-OCI8 on Ubuntu</title>
                <url>/go-oci8-oracle-linux/</url>
            </article>
            <article>
                <category>Server</category>
                <title>Easy Setup OpenVPN Using Docker DockVPN</title>
                <url>/easy-setup-openvpn-docker/</url>
            </article>
            <article info="popular article">
                <category>Server</category>
                <title>Setup Ghost v0.11-LTS, Ubuntu, Nginx, Custom Domain, and SSL</title>
                <url>/ghost-v011-lts-ubuntu-nginx-custom-domain-ssl/</url>
            </article>
        </contents>
    </soap:Body>
</soap:Envelope>
	`

	// 定义结构体捕获根元素的元信息
	var root struct {
		XMLName xml.Name
		Attrs   []xml.Attr `xml:",any,attr"`
	}

	if err := xml.Unmarshal([]byte(xmlData), &root); err != nil {
		fmt.Printf("XML解析失败: %v\n", err)
		return
	}

	// 1. 转换属性为map[string]string
	attrMap := make(map[string]string)
	for _, attr := range root.Attrs {
		key := attr.Name.Local
		if attr.Name.Space != "" {
			key = fmt.Sprintf("%s:%s", attr.Name.Space, key)
		}
		attrMap[key] = attr.Value
	}
	fmt.Println("根元素属性Map:")
	fmt.Printf("%v\n", attrMap)

	// 2. 获取根元素完整名称
	rootName := root.XMLName.Local
	if root.XMLName.Space != "" {
		rootName = fmt.Sprintf("%s:%s", root.XMLName.Space, rootName)
	}
	fmt.Println("\n根元素名称:")
	fmt.Println(rootName)
}

运行结果

根元素属性Map:
map[xmlns:soap:http://schemas.xmlsoap.org/soap/envelope/ xmlns:ns:http://www.opentravel.org/OTA/2003/05]

根元素名称:
soap:Envelope

代码说明

  • 通过xml.Name获取根元素的命名空间和本地名称,拼接后得到带前缀的完整元素名
  • 使用[]xml.Attr配合xml:",any,attr"标签捕获根元素的所有属性,遍历后转换为目标map格式,自动保留属性的命名空间前缀

内容的提问来源于stack exchange,提问作者David Async

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:35:19