3

在遇到 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"`
}
4

1 回答 1

6

xml:",any"你需要在你的CurrencyList领域上的标签。

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

于 2012-06-07T00:50:27.643 回答