XML响应处理
我从eBay API调用获取原始XML响应。现在我必须从XML中获取值并将这些值添加到ViewModel对象,然后将数据返回到我的View。我已经尝试了几件事,但我无法获取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();
}
视图模型:
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>
如果你不使用.NET 3.0或更低,强烈建议使用XDocument
而不是XmlDocument
: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;
由于有大量的检查和比较,写extention方法对于那些将是有益的。
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;
}
...
}
https://ibb.co/hpDPiw检查此屏幕截图。我收到错误:'路径中的非法字符'。 –
你可以给我的网址,以便我可以插入到我的休息客户端? –
//工作网址: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 –
一种方法是从你的XmlDocument
使用XPath查询字符串来访问项目节点值。你可能要循环的响应项目,并创建新的视图模型对象来填充你的ViewModels的列表:
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。
您可以通过[XmlDocument.SelectNodes方法](https://msdn.microsoft.com/en-us/library/system.xml.xmldocument.selectnodes(v = vs.110)的.aspx)。您不应该指定非常复杂的xpath - 有关示例,请参阅[这里](https://www.w3schools.com/xml/xpath_examples.asp)。 – Poosh