2012-06-06 34 views
3

我一直在使用unmarshal沒有任何問題,直到遇到XML標記名稱爲動態的情況。Unmarshal動態XML

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</USD> 
</unit_amount_in_cents> 
<setup_fee_in_cents> 
    <GBP type="integer">4000</USD> 
</setup_fee_in_cents> 

或可能有兩個(或更多)

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

我可以元帥通過指定爲xml W/O問題XML.Name.Local是我所需要的,但不能解組它。

這裏的結構是什麼樣子

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

回答

5

您需要在CurrencyList領域的標籤xml:",any"

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

+0

謝謝,這是我一直在尋找 – MBeale

+0

我想我是太急於說,這解決了我的問題,雖然它確實解組數據正確,採取這一結構,並立即編組它不工作如預期。 http://play.golang.org/p/tO1BPdv8aW – MBeale

+0

@MBeale:這很奇怪。你可能想把它帶到golang-nuts郵件列表。 –