go - 解码动态 XML

标签 go

在遇到 XML 标记名称是动态的情况之前,我一直在使用 unmarshal,没有任何问题。

XML 可能看起来像:

<unit_amount_in_cents>
 <USD type="integer">4000</USD>
</unit_amount_in_cents>
<setup_fee_in_cents>
 <USD type="integer">4000</USD>
</setup_fee_in_cents>

 <unit_amount_in_cents>
  <GBP type="integer">4000</GBP>
 </unit_amount_in_cents>
 <setup_fee_in_cents>
  <GBP type="integer">4000</GBP>
 </setup_fee_in_cents>

或者可以同时拥有(或更多)

<unit_amount_in_cents>
 <USD type="integer">4000</USD>
 <GBP type="integer">4000</GBP>
</unit_amount_in_cents>
<setup_fee_in_cents>
 <USD type="integer">4000</USD>
 <GBP type="integer">4000</USD>
</setup_fee_in_cents>

我可以通过将 XML.Name.Local 分配给我需要的但无法解码它来编码到 xml 而没有问题。

这是结构的样子

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"`
}

type CurrencyArray struct {
    CurrencyList []Currency
}

func (c *CurrencyArray) AddCurrency(currency string, amount int) {
    newc := Currency{Amount:fmt.Sprintf("%v",amount)}
    newc.XMLName.Local = currency
    c.CurrencyList = append(c.CurrencyList, newc)
}

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
}       

type Currency struct {
    XMLName xml.Name `xml:""`
    Amount string `xml:",chardata"`
}

最佳答案

您的 CurrencyList 字段需要标记 xml:",any"

http://play.golang.org/p/i23w03z6R4

关于go - 解码动态 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10922269/

相关文章:

oop - 如何在 Go 中实现一个抽象类?

golang ParseInt int8 不是无符号的

go - 如何在 Go 中计算随机数?

go - 如何释放内存或删除由 http.ParseMultipartForm 创建的临时文件?

function - 如何在 Golang 中访问另一个包的私有(private)函数?

html - 使用 Golang 渲染模板时,不会读取来自不同文件夹的 CSS 和图像

package - 为什么 "go build"找不到包?

go - 在 go 中编码递归类型

json - 将一个 mongodb 对象数组转储到一个结构片段中

Golang OpenSSL 错误的 iv 大小