我目前正在为NameSilo API编写一个库。我被困在XML中,它返回的getPriceList如下所示:
<namesilo>
<request>
<operation>getPrices</operation>
<ip>55.555.55.55</ip>
</request>
<reply>
<code>300</code>
<detail>success</detail>
<com>
<registration>8.99</registration>
<transfer>8.39</transfer>
<renew>8.99</renew>
</com>
<net>
<registration>9.29</registration>
<transfer>8.99</transfer>
<renew>9.29</renew>
</net>
</reply>
</namesilo>如您所见,每个TLD都有一个元素。我想将元素名(例如: com,net)解编组到一个不称为XMLName的属性中(我希望它被称为TLD)。
在阅读了https://golang.org/src/encoding/xml/marshal.go的第34-39行之后,这似乎是不可能的。
我尝试过以下代码,但它不起作用。
type APIResponse struct {
Request struct {
Operation string `xml:"operation"`
IP string `xml:"ip"`
} `xml:"request"`
}
type GetPricesResponse struct {
APIResponse
Reply []struct {
Domains []struct {
TLD xml.name
Registration string `xml:"registration"`
Transfer string `xml:"transfer"`
Renew string `xml:"renew"`
} `xml:",any"`
} `xml:"reply"`
}是否有任何方法可以做到这一点,或者不可能有一个属性名称,而不是XMLName的xml元素名称。
UPDATE:我更深入地研究了代码,并找到了这,这让我觉得我做起来不容易。
发布于 2017-03-20 08:28:49
没有比XMLName xml.Name更简单的选择了。
可以使用满足解组器接口的类型来做您想做的事情。增加的复杂性可能不值得。操场实例
package main
import (
"encoding/xml"
"fmt"
"log"
)
func main() {
var data Data
if err := xml.Unmarshal(payload, &data); err != nil {
log.Fatal(err)
}
for k, v := range data.Reply.Domains {
fmt.Printf("%d: %#v\n", k, v)
}
}
type Domain struct {
TLD string
Registration string `xml:"registration"`
Transfer string `xml:"transfer"`
Renew string `xml:"renew"`
}
func (domain *Domain) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
v := struct {
XMLName xml.Name
Registration string `xml:"registration"`
Transfer string `xml:"transfer"`
Renew string `xml:"renew"`
}{}
d.DecodeElement(&v, &start)
domain.TLD = v.XMLName.Local
domain.Registration = v.Registration
domain.Transfer = v.Transfer
domain.Renew = v.Renew
return nil
}
type Data struct {
Request struct {
Operation string `xml:"operation"`
Ip string `xml:"ip"`
} `xml:"request"`
Reply struct {
Code string `xml:"code"`
Detail string `xml:"detail"`
Domains []Domain `xml:",any"`
} `xml:"reply"`
}
var payload = []byte(`<namesilo>
<request>
<operation>getPrices</operation>
<ip>55.555.55.55</ip>
</request>
<reply>
<code>300</code>
<detail>success</detail>
<com>
<registration>8.99</registration>
<transfer>8.39</transfer>
<renew>8.99</renew>
</com>
<net>
<registration>9.29</registration>
<transfer>8.99</transfer>
<renew>9.29</renew>
</net>
</reply>
</namesilo>`)发布于 2017-03-20 08:21:05
你不需要解压缩到你的最后类型。您可以将其解封为一组反映此数据结构的单独类型,然后将其转换为首选的表示形式,以便在其他地方使用(例如,对于快速查找,您可能希望有一个mapstringPriceRecord将域名映射到价格记录)。我会这样想,而不是一定要在一个步骤中完成转换,这就把您与他们选择产生的任何xml完全联系在一起--如果它改变了,您的数据结构也必须改变。
https://stackoverflow.com/questions/42893752
复制相似问题