解组动态XML

时间:2012-06-06 21:04:12

标签: 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 w / o问题。

这是结构的样子

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

1 个答案:

答案 0 :(得分:5)

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

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