
在go语言中,使用encoding/xml包进行xml解组(unmarshal)通常依赖于结构体字段的xml标签与xml元素的标签名进行匹配。然而,当xml结构中存在动态标签名时,例如表示不同货币类型的子元素,其标签名(如
考虑以下XML片段,其中货币类型(USD, GBP)作为子标签名出现:
<unit_amount_in_cents> <USD type="integer">4000</USD> <GBP type="integer">5000</GBP> </unit_amount_in_cents> <setup_fee_in_cents> <EUR type="integer">6000</EUR> </setup_fee_in_cents>
如果尝试使用如下结构体来解组:
type Currency struct {
XMLName xml.Name `xml:""` // 尝试捕获标签名
Amount string `xml:",chardata"`
}
type CurrencyArray struct {
CurrencyList []Currency `xml:"?"` // 这里需要处理动态标签
}直接将CurrencyList字段映射到某个固定的标签名是不可行的,因为它可能包含任意货币标签。这就是xml:",any"标签发挥作用的场景。
Go语言的encoding/xml包提供了一个特殊的结构体标签选项xml:",any",专门用于处理这种动态子元素的情况。当一个切片(slice)字段被标记为xml:",any"时,解组器会尝试将XML父元素下所有未被其他字段匹配的子元素,按照它们在XML中出现的顺序,解组到该切片中。每个被解组的子元素都会填充切片中对应结构体的xml.Name字段,从而捕获其原始的动态标签名。
立即学习“go语言免费学习笔记(深入)”;
为了演示如何使用xml:",any",我们首先定义一个Currency结构体,它将捕获动态的货币标签名和其值:
package main
import (
"encoding/xml"
"errors"
"fmt"
"strconv"
"time"
)
// Currency 定义了货币元素结构,XMLName用于捕获动态标签名
type Currency struct {
XMLName xml.Name `xml:""` // 捕获动态标签名,如 "USD", "GBP"
Type string `xml:"type,attr"` // 捕获type属性
Amount string `xml:",chardata"` // 捕获元素内容
}
// CurrencyArray 包含一个Currency切片,并使用xml:",any"处理动态子元素
type CurrencyArray struct {
CurrencyList []Currency `xml:",any"` // 关键:使用",any"捕获所有未匹配的子元素
}
// AddCurrency 方法用于向CurrencyArray中添加货币,便于Marshal
func (c *CurrencyArray) AddCurrency(currency string, amount int) {
newc := Currency{Amount: fmt.Sprintf("%v", amount), Type: "integer"}
newc.XMLName.Local = currency // 设置动态标签名
c.CurrencyList = append(c.CurrencyList, newc)
}
// GetCurrencyValue 方法用于从CurrencyArray中获取指定货币的值
func (c *CurrencyArray) GetCurrencyValue(currency string) (value int, e error) {
for _, v := range c.CurrencyList {
if v.XMLName.Local == currency {
value, e = strconv.Atoi(v.Amount)
return
}
}
e = errors.New(fmt.Sprintf("%s not found", currency))
return
}
// Plan 结构体包含动态货币数组
type Plan struct {
XMLName xml.Name `xml:"plan"`
Name string `xml:"name,omitempty"`
PlanCode string `xml:"plan_code,omitempty"`
Description string `xml:"description,omitempty"`
SuccessUrl string `xml:"success_url,omitempty"`
CancelUrl string `xml:"cancel_url,omitempty"`
DisplayDonationAmounts bool `xml:"display_donation_amounts,omitempty"`
DisplayQuantity bool `xml:"display_quantity,omitempty"`
DisplayPhoneNumber bool `xml:"display_phone_number,omitempty"`
BypassHostedConfirmation bool `xml:"bypass_hosted_confirmation,omitempty"`
UnitName string `xml:"unit_name,omitempty"`
PaymentPageTOSLink string `xml:"payment_page_tos_link,omitempty"`
PlanIntervalLength int `xml:"plan_interval_length,omitempty"`
PlanIntervalUnit string `xml:"plan_interval_unit,omitempty"`
AccountingCode string `xml:"accounting_code,omitempty"`
CreatedAt *time.Time `xml:"created_at,omitempty"`
SetupFeeInCents CurrencyArray `xml:"setup_fee_in_cents,omitempty"` // 包含动态货币数组
UnitAmountInCents CurrencyArray `xml:"unit_amount_in_cents,omitempty"` // 包含动态货币数组
}
func main() {
// 示例XML数据,包含动态货币标签
xmlData := `
<plan>
<name>Basic Plan</name>
<plan_code>BP001</plan_code>
<setup_fee_in_cents>
<USD type="integer">4000</USD>
<GBP type="integer">3500</GBP>
</setup_fee_in_cents>
<unit_amount_in_cents>
<USD type="integer">1000</USD>
<EUR type="integer">900</EUR>
</unit_amount_in_cents>
</plan>`
var plan Plan
err := xml.Unmarshal([]byte(xmlData), &plan)
if err != nil {
fmt.Printf("Unmarshal error: %v\n", err)
return
}
fmt.Println("--- Unmarshaled Plan Data ---")
fmt.Printf("Plan Name: %s\n", plan.Name)
fmt.Printf("Plan Code: %s\n", plan.PlanCode)
fmt.Println("\nSetup Fee In Cents:")
for _, c := range plan.SetupFeeInCents.CurrencyList {
fmt.Printf(" Currency: %s, Amount: %s, Type: %s\n", c.XMLName.Local, c.Amount, c.Type)
}
usdSetupFee, err := plan.SetupFeeInCents.GetCurrencyValue("USD")
if err == nil {
fmt.Printf(" USD Setup Fee: %d\n", usdSetupFee)
}
fmt.Println("\nUnit Amount In Cents:")
for _, c := range plan.UnitAmountInCents.CurrencyList {
fmt.Printf(" Currency: %s, Amount: %s, Type: %s\n", c.XMLName.Local, c.Amount, c.Type)
}
eurUnitAmount, err := plan.UnitAmountInCents.GetCurrencyValue("EUR")
if err == nil {
fmt.Printf(" EUR Unit Amount: %d\n", eurUnitAmount)
}
// 演示Marshal回XML
fmt.Println("\n--- Marshaling back to XML ---")
// 假设我们修改或添加一些数据
plan.UnitAmountInCents.AddCurrency("JPY", 12000)
plan.SetupFeeInCents.AddCurrency("CAD", 3000)
outputXML, err := xml.MarshalIndent(plan, "", " ")
if err != nil {
fmt.Printf("Marshal error: %v\n", err)
return
}
fmt.Println(string(outputXML))
}代码解析:
运行上述代码,你将看到动态的货币标签(如USD, GBP, EUR)及其对应的金额被正确地解析和打印出来。同时,也展示了如何通过AddCurrency方法在程序中构建数据并将其重新Marshal为XML,验证了XMLName.Local在Marshal时的作用。
通过巧妙地利用Go语言encoding/xml包提供的xml:",any"标签,结合结构体中的xml.Name字段,我们可以优雅地解决XML解组过程中遇到的动态标签名问题。这种方法不仅简化了代码,还提高了程序的灵活性和可维护性,使得Go语言在处理复杂、多变的XML数据时更加得心应手。理解并掌握xml:",any"的使用,是Go开发者处理高级XML解析任务的重要技能。
以上就是Go语言中处理动态XML标签的Unmarshal教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号