
在go语言中进行xml解析时,我们通常会将xml元素映射到预定义的go结构体字段。然而,当xml结构中的某些标签名是动态生成,例如表示货币类型(usd, gbp, eur)的标签时,传统的固定标签映射方式就会遇到困难。本文将详细介绍如何利用encoding/xml包提供的xml:",any"标签来优雅地解决这一问题。
考虑以下XML片段,其中<unit_amount_in_cents>和<setup_fee_in_cents>下的子元素标签名是动态的货币代码:
<unit_amount_in_cents> <USD type="integer">4000</USD> <GBP type="integer">3000</GBP> </unit_amount_in_cents> <setup_fee_in_cents> <EUR type="integer">5000</EUR> <USD type="integer">6000</USD> </setup_fee_in_cents>
在这种情况下,子元素(如<USD>、<GBP>、<EUR>)的标签名本身就是数据的一部分。如果尝试使用如下结构体进行解析:
type Currency struct {
XMLName xml.Name `xml:""` // 尝试捕获标签名
Amount string `xml:",chardata"`
}
type CurrencyArray struct {
CurrencyList []Currency
}xml.Unmarshal将无法识别CurrencyList中的每个Currency元素应该对应哪个动态标签。它期望一个固定的标签名来匹配CurrencyList中的元素。
Go语言的encoding/xml包提供了一个特殊的结构体标签选项xml:",any",它允许我们将任何未匹配的子元素解析到一个切片字段中。当与xml.Name字段结合使用时,它能够完美地捕获动态标签名及其内容。
立即学习“go语言免费学习笔记(深入)”;
为了正确解析上述动态XML,我们需要对Currency和CurrencyArray结构体进行如下修改:
Currency 结构体:
CurrencyArray 结构体:
修改后的结构体定义如下:
import "encoding/xml"
// Currency 结构体用于捕获动态标签名、属性和内容
type Currency struct {
XMLName xml.Name // 捕获动态标签名 (e.g., "USD", "GBP")
Type string `xml:"type,attr"` // 捕获 type 属性
Amount string `xml:",chardata"` // 捕获元素内容
}
// CurrencyArray 结构体使用 xml:",any" 捕获所有子货币元素
type CurrencyArray struct {
CurrencyList []Currency `xml:",any"` // 使用 ,any 捕获所有子元素
}
// Plan 结构体保持不变,但其内部引用了修改后的 CurrencyArray
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"`
}在上述Currency结构体中:
以下是一个完整的Go程序,演示了如何使用修改后的结构体解析包含动态标签的XML数据,并提取所需信息:
package main
import (
"encoding/xml"
"fmt"
"strconv"
"time"
)
// Currency 结构体用于捕获动态标签名、属性和内容
type Currency struct {
XMLName xml.Name // 捕获动态标签名 (e.g., "USD", "GBP")
Type string `xml:"type,attr"` // 捕获 type 属性
Amount string `xml:",chardata"` // 捕获元素内容
}
// CurrencyArray 结构体使用 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"} // 添加 type 属性
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 = fmt.Errorf("currency %s not found", currency)
return
}
// Plan 结构体保持不变,但其内部引用了修改后的 CurrencyArray
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>basic</plan_code>
<setup_fee_in_cents>
<USD type="integer">4000</USD>
<GBP type="integer">3000</GBP>
</setup_fee_in_cents>
<unit_amount_in_cents>
<EUR type="integer">5000</EUR>
<USD type="integer">6000</USD>
</unit_amount_in_cents>
</plan>`
var p Plan
err := xml.Unmarshal([]byte(xmlData), &p)
if err != nil {
fmt.Printf("Unmarshal error: %v\n", err)
return
}
fmt.Println("--- Unmarshaled Plan Data ---")
fmt.Printf("Plan Name: %s\n", p.Name)
fmt.Printf("Plan Code: %s\n", p.PlanCode)
fmt.Println("\nSetup Fee in Cents:")
for _, c := range p.SetupFeeInCents.CurrencyList {
fmt.Printf(" Currency: %s, Type: %s, Amount: %s\n", c.XMLName.Local, c.Type, c.Amount)
}
usdSetupFee, err := p.SetupFeeInCents.GetCurrencyValue("USD")
if err == nil {
fmt.Printf(" Retrieved USD Setup Fee: %d\n", usdSetupFee)
} else {
fmt.Printf(" Error getting USD Setup Fee: %v\n", err)
}
fmt.Println("\nUnit Amount in Cents:")
for _, c := range p.UnitAmountInCents.CurrencyList {
fmt.Printf(" Currency: %s, Type: %s, Amount: %s\n", c.XMLName.Local, c.Type, c.Amount)
}
eurUnitAmount, err := p.UnitAmountInCents.GetCurrencyValue("EUR")
if err == nil {
fmt.Printf(" Retrieved EUR Unit Amount: %d\n", eurUnitAmount)
} else {
fmt.Printf(" Error getting EUR Unit Amount: %v\n", err)
}
}运行上述代码将输出:
--- Unmarshaled Plan Data --- Plan Name: Basic Plan Plan Code: basic Setup Fee in Cents: Currency: USD, Type: integer, Amount: 4000 Currency: GBP, Type: integer, Amount: 3000 Retrieved USD Setup Fee: 4000 Unit Amount in Cents: Currency: EUR, Type: integer, Amount: 5000 Currency: USD, Type: integer, Amount: 6000 Retrieved EUR Unit Amount: 5000
可以看到,xml:",any"标签成功地将<USD>、<GBP>、<EUR>等动态标签解析到了CurrencyList切片中,并且每个Currency结构体实例的XMLName.Local字段正确地包含了相应的货币代码。
以上就是Go语言中处理动态XML标签的Unmarshal技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号