У меня есть 2 очень похожих фрагмента XML, полученных из Amazon.
<?xml version="1.0"?><GetLowestPricedOffersForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetLowestPricedOffersForASINResult MarketplaceID="A1F83G8C2ARO7P" ItemCondition="New" ASIN="0195019199" status="Success">
<Identifier>
<MarketplaceId>A1F83G8C2ARO7P</MarketplaceId>
<ASIN>0195019199</ASIN>
<ItemCondition>New</ItemCondition>
<TimeOfOfferChange>2018-11-07T02:05:14.342Z</TimeOfOfferChange>
</Identifier>
<Summary>
<TotalOfferCount>45</TotalOfferCount>
<NumberOfOffers>
<OfferCount condition="used" fulfillmentChannel="Merchant">14</OfferCount>
<OfferCount condition="new" fulfillmentChannel="Amazon">1</OfferCount>
<OfferCount condition="new" fulfillmentChannel="Merchant">30</OfferCount>
</NumberOfOff........ etc xml continues
</GetLowestPricedOffersForASINResult>
<ResponseMetadata>
<RequestId>fef8c86d-c563-4373-81c9-78dcf691283c</RequestId>
</ResponseMetadata>
</GetLowestPricedOffersForASINResponse>
В настоящее время я демонтирую это, используя пользовательские типы и пользовательские демаршалы в структуру, которая выглядит следующим образом:
type LowestPricedPricedOffers struct {
Error AmazonError `xml:"Error"`
All struct {
/*The only way I found to retrieve 'status' from the GetLowestPricedOffersForASINResult element was to wrap in the struct 'All'.
This is the only reason the All struct exists. Ideally would like to remove*/
Status string `xml:"status,attr"`
ASIN string `xml:"Identifier>ASIN"`
ItemCondition string `xml:"Identifier>ItemCondition"`
TimeOfOfferChange string `xml:"Identifier>TimeOfOfferChange"`
TotalOfferCount int `xml:"Summary>TotalOfferCount"`
ListPrice float32 `xml:"Summary>ListPrice>Amount"`
OfferCount offerCount `xml:"Summary>NumberOfOffers"`
//Want to take Currency code from LowestPrices below but cannot think of a way to achieve this against the lowestPrices type
//CurrencyCode string `xml:"CurrencyCode"`
BuyBoxPrices buyBoxPrices `xml:"Summary>BuyBoxPrices"`
LowestPrices lowestPrices `xml:"Summary>LowestPrices"`
BuyBoxEligibleOffers buyBoxEligibleOffers `xml:"Summary>BuyBoxEligibleOffers"`
Offers []struct {
SubCondition string `xml:"SubCondition"`
SellerPositiveFeedbackRating float32 `xml:"SellerFeedbackRating>SellerPositiveFeedbackRating"`
FeedbackCount int `xml:"SellerFeedbackRating>FeedbackCount"`
ShippingTime struct {
MinimumHours int `xml:"minimumHours,attr"`
MaximumHours int `xml:"maximumHours,attr"`
AvailabilityType string `xml:"availabilityType,attr"`
}
ListingPrice float32 `xml:"ListingPrice>Amount"`
Shipping float32 `xml:"Shipping>Amount"`
ShipsFrom string `xml:"ShipsFrom>Country"`
IsFulfilledByAmazon bool `xml:"IsFulfilledByAmazon"`
IsBuyBoxWinner bool `xml:"IsBuyBoxWinner"`
IsFeaturedMerchant bool `xml:"IsFeaturedMerchant"` //true if the seller of the item is eligible to win the Buy Box.
} `xml:"Offers>Offer"`
} `xml:"GetLowestPricedOffersForASINResult"`
}
У меня также есть еще несколько XML-данных, структура которых одинакова, за исключением того, что элемент 'GetLowestPricedOffersForASINResult' называется 'GetLowestPricedOffersForSKUResult'.
Если я изменю вручную, изменим тег xml:"GetLowestPricedOffersForASINResult"
на xml:"GetLowestPricedOffersForSKUResult"
, тогда код успешно обработает другой XML.
Я хотел бы сделать это универсальным, если хотите, мои варианты выглядят так:
Скопируйте код и получите 2 больших блока, которые в основном одинаковы. Это было бы легко, но мне кажется, что это неправильный подход.
Внедрите его, выполнив поиск и замену необработанной строки XML и просто заменив GetLowestPricedOffersForSKUResult на GetLowestPricedOffersForASINResult, после чего код будет обрабатывать данные счастливо, опять же, это кажется неправильным.
Измените тег struct на лету, возможно, используя отражение. Возможно ли это?
Есть ли у кого-нибудь предложения по реализации 3 или других идей / подходов для решения этой проблемы на ходу?
Код для набора результатов GetLowestPricedOffersForASINResult находится на go площадке (не завершено, но работает)