douqie1852
2017-03-29 18:00
浏览 163

golang:省略xml.Marshal中的struct名称

Trying to get a particular output for XML:

<RESPONSE>
    <DELIMITER value="09"></DELIMITER>
    <COLUMNS>Id FirstName   LastName    Company Initials</COLUMNS>
     <DATA>87734    Some Guy    Keller Williams Realty Empire   </DATA>
     <DATA>87739    Another Guy Level Group, Inc.   </DATA>
     <DATA>87741    Some Gal    Kian Realty NYC, LLC    </DATA>
</RESPONSE> 

instead I am getting:

<RESPONSE>
 <compactData>
        <DELIMITER value="09"></DELIMITER>
        <COLUMNS>Id FirstName   LastName    Company Initials</COLUMNS>
        <DATA>87734 Some Guy    Keller Williams Realty Empire   </DATA>
        <DATA>87739 Another Guy Level Group, Inc.   </DATA>
        <DATA>87741 Some Gal    Kian Realty NYC, LLC    </DATA>
 </compactData>
</RESPONSE> 

I am trying not to output the <compactData> tag at all. (everything else is a-ok)

my struct that I am marshal-ing looks like this:

type delimiter struct {
    Value string `xml:"value,attr"`
}

type innerData struct {
    Data string `xml:",innerxml"`
}

type compactData struct {
    Delimiter delimiter    `xml:"DELIMITER"`
    Columns   *innerData   `xml:"COLUMNS"`
    Records   []*innerData `xml:"DATA"`
}

I have tried putting in

XMLName   xml.Name

or

XMLName   xml.Name `xml:""`

to no avail- the xml.MarshalIndent just says 'yeah that looks like crap taking the struct name instead'.

I feel as though I just may need to reorganize the struct a bit, but I am stumped as to the magic structure needed.

Thanks!

Edit: the <RESPONSE> tag is added as the http.reponse is sent, after this formatting is done, trying to keep this signature the same as JSON and XML encoding...

like so:

func createResponse(obj interface{}, format string) (*Response, error) {
    var data []byte

    var f func(interface{}, string, string) ([]byte, error)

    switch format {
    case FORMAT_JSON:
        f = json.MarshalIndent
    case FORMAT_COMPACT:
        f = compact.MarshalIndent
    default:
        f = xml.MarshalIndent
    }
    data, err := f(obj, " ", "    ")
    if err != nil {
        log.Println(err)
        return nil, err
    }
    return &Response{Data: string(data)}, nil

}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dqypcghd381390 2017-03-29 18:35
    最佳回答

    If RESPONSE is another struct you could embed compactData in it and let encoding/xml do what you want.

    type RESPONSE struct {
        compactData
    }
    

    https://play.golang.org/p/hN1hDY7pnV

    Update: Actually you can do what you want, if I understood you correctly, by implementing the xml.Marshaler interface. E.g. something like this: https://play.golang.org/p/Uwm0pP1pWh.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题