Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# XML响应处理_C#_Asp.net Mvc - Fatal编程技术网

C# XML响应处理

C# XML响应处理,c#,asp.net-mvc,C#,Asp.net Mvc,我从eBay API调用中获得原始XML响应。现在我必须从XML中获取值,并将这些值添加到ViewModel对象,然后将数据返回到视图中。我已经尝试了以下几项,但我无法获取XML响应项并将其分配给ViewModel。请检查下面代码的每一部分,如果您有任何解决方案,请告诉我。我不需要工作代码,因为我知道你不能测试它,因为它尚未完成。不过,简单的提示就足够了,我对c#还不熟悉。提前多谢 控制器: public ActionResult Search(string OperationName, str

我从eBay API调用中获得原始XML响应。现在我必须从XML中获取值,并将这些值添加到ViewModel对象,然后将数据返回到视图中。我已经尝试了以下几项,但我无法获取XML响应项并将其分配给ViewModel。请检查下面代码的每一部分,如果您有任何解决方案,请告诉我。我不需要工作代码,因为我知道你不能测试它,因为它尚未完成。不过,简单的提示就足够了,我对c#还不熟悉。提前多谢

控制器:

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();
        }
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>

-
成功
1.13.0
2017-10-14T08:27:04.876Z
-
-
332390426668
حجاب روحاني يتحرك,حجاب الغزال أوالظبي ,أقوى حجاب للمحبة والزواج ,حرز حي يتفاعل 
易趣美国
-
162918
伊斯兰的
http://thumbs1.ebaystatic.com/m/mf7QDRtgSn83eQF23aLFD_Q/140.jpg
http://www.ebay.com/itm/-/332390426668
贝宝
真的
04468
美国老城
美国
-
0
国际公寓
在全世界
假的
假的
1.
-
350
350
活跃的
P10DT14H19M17S
-
真的
假的
2017-09-24T22:46:21.000Z
2017-10-24T22:46:21.000Z
库存
假的
6.
真的
http://galleryplus.ebayimg.com/ws/web/332390426668_1_1_1.jpg
假的
假的
-
382249935959
大约公元900年,在拉脱维亚出土的真迹维京青铜蛇手镯
易趣美国
-
162920
维京人
http://thumbs4.ebaystatic.com/m/mf73oCtiHN2GGSZlIY0VP7Q/140.jpg
http://www.ebay.com/itm/Circa-900-AD-Authentic-Viking-Bronze-Snake-Bracelet-Found-Latvia-Excavation-/382249935959
贝宝
真的
80932
美国科罗拉多州斯普林斯
美国
-
0
自由的
在全世界
假的
假的
1.
-
52
52
活跃的
P28DT14H3M39S
-
假的
假的
2017-10-12T22:30:43.000Z
2017-11-11T22:30:43.000Z
固定价格
假的
1.
真的
假的
真的
-
1.
2.
27113
54226
http://www.ebay.com/sch/37903/i.html?_ddo=1&_ipg=2&_pgn=1

如果您没有使用.NET 3.0版或更低版本,强烈建议在
XmlDocument
上使用
XDocument

无论如何,您可以使用
.subjections()
获取所有子体,然后比较其所有元素的本地名称,以查看是否有一个元素的本地名称与项的名称匹配

(已测试)

var items=newlist();
//可以使用.Load()方法直接插入url。
//无需创建HttpClient以字符串形式下载响应,然后
//解析。
XDocument xdoc=XDocument.Load(url);
//因为你只对收藏感兴趣
var searchResultItems=xdoc.subjects()
。其中(x=>x.Name.LocalName==“项”);
foreach(searchResultItems中的var sri)
{
//获取所有子xml元素
var childElements=sri.Elements();
var itemId=childElements.FirstOrDefault(x=>x.Name.LocalName==“itemId”);
var title=childElements.FirstOrDefault(x=>x.Name.LocalName==“title”);
//将xml数据中的项添加到EbayDataViewModel对象
items.Add(新的EbayDataViewModel{
EbayTitle=title==null?Stirng.Empty:title.Value,
...
});
}
退货项目;
因为有很多检查和比较,所以为这些检查和比较编写扩展方法将非常有用。

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;
    }

    ...
}
公共静态类XelementTextensions
{
公共静态XElement LocalNameElement(此XElement父级,字符串localName)
{
返回parent.Elements().FirstOrDefault(x=>x.Name.LocalName==LocalName);
公共静态IEnumerable LocalNameElements(此XElement父项,字符串localName)
{
返回parent.Elements(),其中(x=>x.Name.LocalName==LocalName);
}
公共静态字符串LocalNameElementValue(此XElement父项,字符串localName)
{
var-element=parent.localnamelement(localName);
返回元素==null?字符串。空:element.Value;
}
...
}

一种方法是使用XPath查询字符串从
XmlDocument
访问项节点值。您可能希望循环响应项并创建新的ViewModel对象以填充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
        });
}
var items=newlist();
var responseItems=xdoc.SelectNodes(“项”);
foreach(responseItems中的responseItem)
{
添加(新的EbayDataViewModel()
{EbayImageUrl=responseItem.SelectSingleNode(“galleryURL”).InnerText,
ebayitle=responseItem.SelectSingleNode(“标题”).InnerText,
NumberOfSales=responseItem。选择SingleNode(“”)。InnerText,
NumberOfWatch=responseItem。选择SingleNode(“”)。InnerText
});
}
注意:我在XML响应中找不到任何类似“NumberOfSales或NumberOfWatch”的内容,因此需要填写这些XPath


有关此方法的文档,请参阅。

检查此屏幕截图。我收到错误:“路径中的非法字符”。您能给我url以便我可以将其插入Rest客户端吗?//工作url:任何解决方案?@David LiangNo,您只需将url直接插入
XDocument.Load()
。您不需要创建客户端并将响应作为字符串下载。@JohnLkYou可以访问
XmlDocument
中的值来使用来填充模型。您不必指定非常复杂的xpath-有关一些示例,请参阅。
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;
    }

    ...
}
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
        });
}