daino3
daino3

Reputation: 4566

Golang nested, renamed XML attributes

Given the following struct:

type book struct {
    XMLName xml.Name   `xml:"DailyAct"`
    Symbol     string  `xml:"TradeInstrId,attr"`
    EntityId   string  `xml:"EntityId,attr"`
    AssetClass string  `xml:"AssetClass,attr"`
    Open       int     `xml:"Open"`
    High       int     `xml:"High"`
    Low        int     `xml:"Low"`
    Close      int     `xml:"Close"`
    // Type      string `` //I'll leave this for another question
}

My current XML:

  <DailyAct EntityId="foo" AssetClass="bar" TradeInstrId="Symbol" >
      <Open>2</Open>
      <High>3</High>
      <Low>1</Low>
      <Close>5</Close>
  </DailyAct>

But, I need to repurpose certain fields of the struct (or generate xml another way) to achieve:

<DailyAct EntityId="foo" AssetClass="bar" TradeInstrId="Symbol">
  <Open Price="2" Type="IND"/>
  <High Price="6" Type="IND"/>
  <Low Price="1" Type="IND"/>
  <Close Price="4" Type="IND"/>
</DailyAct>

But I get: &errors.errorString{s:"xml: DailyAct>Open chain not valid with Price,attr flag"} (actual) when I try to nest fields like so:

type book struct {
    //...
    Open       int     `xml:"DailyAct>Open,Price,attr>"`
    //...
}

Edit: I found this discussion, while googling around so what I'm going for may not be feasible currently

Upvotes: 1

Views: 2430

Answers (1)

CrazyCrow
CrazyCrow

Reputation: 4235

You are right currently it's impossible. But you can use sub-structures like

type PriceType struct {
    Price int    `xml:"Price,attr"`
    Type  string `xml:"Type,attr"`
}

type Book struct {
    XMLName    xml.Name  `xml:"DailyAct"`
    Symbol     string    `xml:"TradeInstrId,attr"`
    EntityId   string    `xml:"EntityId,attr"`
    AssetClass string    `xml:"AssetClass,attr"`
    Open       PriceType `xml:"Open"`
    High       PriceType `xml:"High"`
    Low        PriceType `xml:"Low"`
    Close      PriceType `xml:"Close"`
}

Example here http://play.golang.org/p/Ekd6Xf3miS

Upvotes: 6

Related Questions