2017-10-14 10 views
2

eBay APIコールから生のXML応答を取得しています。 XMLから値を取得し、その値をViewModelオブジェクトに追加してから、データをビューに戻す必要があります。私はすでにいくつかのことを試してみましたが、XML応答項目を取得してViewModelに割り当てることができません。下記のコードの各部分を確認し、解決策がある場合は教えてください。私は作業コードを必要としません。私はあなたがそれが未完成のテストができないことを知っている。しかし、単純なヒントだけで十分ですが、私はC#で新しいです。事前のおかげでたくさんのXML応答処理

コントローラー:

public ActionResult Search(string OperationName, string calltype, string page, string keywords, string type, string location, string condition, string min, string max, string negative, string minFeedback, string maxFeedback, string drange, string categoryId) 
     { 
      string AppId = "KavinHim-BestProd-PRD-785446bf1-666"; //api configs 
      string BaseUrl = "http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME="; //base url api end point 

      if (calltype == "categoryClick") 
      { 
       string Url = BaseUrl + OperationName + "&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=" + AppId + "&RESPONSE-DATA-FORMAT=XML&REST-PAYLOAD&categoryId=" + categoryId + "&paginationInput.entriesPerPage=2&paginationInput.pageNumber=" + page + ""; 
       var client = new RestClient(Url); 
       var request = new RestRequest(Method.GET); 
       request.Method = Method.GET; 
       request.Parameters.Clear(); 
       var xmlResponse = client.Execute(request).Content; 

       XmlDocument xdoc = new XmlDocument(); 
       xdoc.LoadXml(new WebClient().DownloadString(xmlResponse)); 


       var items = new List<EbayDataViewModel>(); 

       foreach (var item in items) 
       { 
        //add items from xml data to EbayDataViewModel object 

       } 

      } 
      return View(); 
     } 

のViewModel:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using WebApplication2.Models; 

namespace WebApplication2.ViewModels 
{ 
    public class EbayDataViewModel 
    { 
     public string EbayImageUrl { get; set; } 
     public string EbayTitle { get; set; } 
     public string NumberOfSales { get; set; } 
     public string NumberOfWatch { get; set; } 
    } 


} 

XML応答:

<?xml version="1.0" encoding="UTF-8"?> 

-<findItemsByCategoryResponse xmlns="http://www.ebay.com/marketplace/search/v1/services"> 

<ack>Success</ack> 

<version>1.13.0</version> 

<timestamp>2017-10-14T08:27:04.876Z</timestamp> 


-<searchResult count="2"> 


-<item> 

<itemId>332390426668</itemId> 

<title>حجاب روحاني يتحرك,حجاب الغزال أوالظبي ,أقوى حجاب للمحبة والزواج ,حرز حي يتفاعل </title> 

<globalId>EBAY-US</globalId> 


-<primaryCategory> 

<categoryId>162918</categoryId> 

<categoryName>Islamic</categoryName> 

</primaryCategory> 

<galleryURL>http://thumbs1.ebaystatic.com/m/mf7QDRtgSn83eQF23aLFD_Q/140.jpg</galleryURL> 

<viewItemURL>http://www.ebay.com/itm/-/332390426668</viewItemURL> 

<paymentMethod>PayPal</paymentMethod> 

<autoPay>true</autoPay> 

<postalCode>04468</postalCode> 

<location>Old Town,ME,USA</location> 

<country>US</country> 


-<shippingInfo> 

<shippingServiceCost currencyId="USD">0.0</shippingServiceCost> 

<shippingType>FlatDomesticCalculatedInternational</shippingType> 

<shipToLocations>Worldwide</shipToLocations> 

<expeditedShipping>false</expeditedShipping> 

<oneDayShippingAvailable>false</oneDayShippingAvailable> 

<handlingTime>1</handlingTime> 

</shippingInfo> 


-<sellingStatus> 

<currentPrice currencyId="USD">350.0</currentPrice> 

<convertedCurrentPrice currencyId="USD">350.0</convertedCurrentPrice> 

<sellingState>Active</sellingState> 

<timeLeft>P10DT14H19M17S</timeLeft> 

</sellingStatus> 


-<listingInfo> 

<bestOfferEnabled>true</bestOfferEnabled> 

<buyItNowAvailable>false</buyItNowAvailable> 

<startTime>2017-09-24T22:46:21.000Z</startTime> 

<endTime>2017-10-24T22:46:21.000Z</endTime> 

<listingType>StoreInventory</listingType> 

<gift>false</gift> 

<watchCount>6</watchCount> 

</listingInfo> 

<returnsAccepted>true</returnsAccepted> 

<galleryPlusPictureURL>http://galleryplus.ebayimg.com/ws/web/332390426668_1_1_1.jpg</galleryPlusPictureURL> 

<isMultiVariationListing>false</isMultiVariationListing> 

<topRatedListing>false</topRatedListing> 

</item> 


-<item> 

<itemId>382249935959</itemId> 

<title>Circa 900 AD Authentic Viking Bronze Snake Bracelet Found In Latvia Excavation</title> 

<globalId>EBAY-US</globalId> 


-<primaryCategory> 

<categoryId>162920</categoryId> 

<categoryName>Viking</categoryName> 

</primaryCategory> 

<galleryURL>http://thumbs4.ebaystatic.com/m/mf73oCtiHN2GGSZlIY0VP7Q/140.jpg</galleryURL> 

<viewItemURL>http://www.ebay.com/itm/Circa-900-AD-Authentic-Viking-Bronze-Snake-Bracelet-Found-Latvia-Excavation-/382249935959</viewItemURL> 

<paymentMethod>PayPal</paymentMethod> 

<autoPay>true</autoPay> 

<postalCode>80932</postalCode> 

<location>Colorado Springs,CO,USA</location> 

<country>US</country> 


-<shippingInfo> 

<shippingServiceCost currencyId="USD">0.0</shippingServiceCost> 

<shippingType>Free</shippingType> 

<shipToLocations>Worldwide</shipToLocations> 

<expeditedShipping>false</expeditedShipping> 

<oneDayShippingAvailable>false</oneDayShippingAvailable> 

<handlingTime>1</handlingTime> 

</shippingInfo> 


-<sellingStatus> 

<currentPrice currencyId="USD">52.0</currentPrice> 

<convertedCurrentPrice currencyId="USD">52.0</convertedCurrentPrice> 

<sellingState>Active</sellingState> 

<timeLeft>P28DT14H3M39S</timeLeft> 

</sellingStatus> 


-<listingInfo> 

<bestOfferEnabled>false</bestOfferEnabled> 

<buyItNowAvailable>false</buyItNowAvailable> 

<startTime>2017-10-12T22:30:43.000Z</startTime> 

<endTime>2017-11-11T22:30:43.000Z</endTime> 

<listingType>FixedPrice</listingType> 

<gift>false</gift> 

<watchCount>1</watchCount> 

</listingInfo> 

<returnsAccepted>true</returnsAccepted> 

<isMultiVariationListing>false</isMultiVariationListing> 

<topRatedListing>true</topRatedListing> 

</item> 

</searchResult> 


-<paginationOutput> 

<pageNumber>1</pageNumber> 

<entriesPerPage>2</entriesPerPage> 

<totalPages>27113</totalPages> 

<totalEntries>54226</totalEntries> 

</paginationOutput> 

<itemSearchURL>http://www.ebay.com/sch/37903/i.html?_ddo=1&_ipg=2&_pgn=1</itemSearchURL> 

</findItemsByCategoryResponse> 
+0

[XmlDocument.SelectNodesメソッド](https://msdn.microsoft.com/en-us/library/system.xml.xmldocument.selectnodes(v = 0))を使用して、 vs.110).aspx)。非常に複雑なxpathを指定する必要はありません。いくつかの例については、[here](https://www.w3schools.com/xml/xpath_examples.asp)を参照してください。 – Poosh

答えて

1

あなたは.NETバージョン3.0以下を使用していない場合は、 XDocumentXmlDocument以上に使用することを強くお勧めします。reference link

とにかく、あなたはすべての子孫を取得するために.Descendants()を使用することができ、その後、そのローカル名項目の名前と一致する要素があるかどうかを確認するために、そのすべての要素のローカル名を比較します。

(テスト済み)

var items = new List<EbayDataViewModel>(); 

// You can directly plug the url in with .Load() method. 
// No need to create HttpClient to download the response as string and then 
// parse. 
XDocument xdoc = XDocument.Load(url); 

// Since you're only interested in <item> collections within <searchResult> 
var searchResultItems = xdoc.Descendants() 
    .Where(x => x.Name.LocalName == "item"); 

foreach (var sri in searchResultItems) 
{ 
    // Get all child xml elements 
    var childElements = sri.Elements(); 

    var itemId = childElements.FirstOrDefault(x => x.Name.LocalName == "itemId"); 
    var title = childElements.FirstOrDefault(x => x.Name.LocalName == "title"); 

    //add items from xml data to EbayDataViewModel object 
    items.Add(new EbayDataViewModel { 
     EbayTitle = title == null? Stirng.Empty : title.Value, 
     ... 
    }); 
} 

return items; 

チェックや比較がたくさんあるので、それらのための拡張子のメソッドを記述することは有用であろう。

public static class XElementExtensions 
{ 
    public static XElement LocalNameElement(this XElement parent, string localName) 
    { 
     return parent.Elements().FirstOrDefault(x => x.Name.LocalName == localName); 

    public static IEnumerable<XElement> LocalNameElements(this XElement parent, string localName) 
    { 
     return parent.Elements().Where(x => x.Name.LocalName == localName); 
    } 

    public static string LocalNameElementValue(this XElement parent, string localName) 
    { 
     var element = parent.LocalNameElement(localName); 
     return element == null? String.Empty : element.Value; 
    } 

    ... 
} 
+0

https://ibb.co/hpDPiwこのスクリーンショットを確認してください。私はエラーが発生しています: 'パスの不正な文字。' –

+0

私はあなたのレストクライアントに接続できるように私にURLを教えてもらえますか? –

+0

//作業URL:http://svcs.ebay.com/services/search/FindingService/v1?OPERATION-NAME=findItemsByCategory&SERVICE-VERSION=1.0.0&SECURITY-APPNAME=KavinHim-BestProd-PRD-78e3e6bf1-97d9ef25&RESPONSE-DATA- FORMAT = XML&REST-PAYLOAD&categoryId = 37903&paginationInput.entriesPerPage = 100&paginationInput.pageNumber = 4 –

0

一つの方法は、XPathクエリ文字列を使用してXmlDocumentから項目ノード値にアクセスすることになります。あなたは、おそらくのviewmodelsのリストを投入するために、応答項目をループにしたいと新しいのViewModelオブジェクトを作成します:

var items = new List<EbayDataViewModel>(); 
var responseItems = xdoc.SelectNodes("item"); 
foreach (responseItem in responseItems) 
{ 
    items.Add(new EbayDataViewModel() 
     { EbayImageUrl = responseItem.SelectSingleNode("galleryURL").InnerText, 
      EbayTitle = responseItem.SelectSingleNode("title").InnerText, 
      NumberOfSales = responseItem.SelectSingleNode("").InnerText, 
      NumberOfWatch = responseItem.SelectSingleNode("").InnerText 
     }); 
} 

注:私は、XML応答で「NumberOfSalesまたはNumberOfWatch」のように見えた何かを見つけることができませんでしたこれらのXPathを記入する必要があります。

このメソッドのドキュメントについては、XmlDocument.SelectNodesを参照してください。