No elements found when parsing eBay's api result xml
I'm trying to search eBay via C# and XML. I can see that I'm getting a valid XML response, by writing out the XML to a string, but cannot parse it using C# - I just keep getting told that there are no elements.
Here's my code, with my appname key removed:
string xmldata = "<?xml version='1.0' encoding='utf-8'?>";
xmldata += "<findItemsAdvancedRequest xmlns='http://www.ebay.com/marketplace/search/v1/services'>";
xmldata += "<keywords>sneakers</keywords>";
xmldata += "<categoryId>1</categoryId>";
xmldata += "<descriptionSearch>false</descriptionSearch>";
xmldata += "<paginationInput>";
xmldata += "<entriesPerPage>5</entriesPerPage>";
xmldata += "</paginationInput>";
xmldata += "</findItemsAdvancedRequest>";
string url = "http://svcs.ebay.com/services/search/FindingService/v1";
//Create a HttpWebRequest object
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
//Convert xml string to a byte array
byte[] postDataBytes = Encoding.ASCII.GetBytes(xmldata);
//Set the Method property
req.Method = "POST";
//Set the ContentType property of the "HttpWebRequest"
req.ContentType = "text/xml;charset=UTF-8";
req.Headers.Add("X-EBAY-SOA-SERVICE-NAME", "FindingService");
req.Headers.Add("X-EBAY-SOA-OPERATION-NAME", "findItemsAdvanced");
req.Headers.Add("X-EBAY-SOA-SERVICE-VERSION", "1.4.0");
req.Headers.Add("X-EBAY-SOA-GLOBAL-ID", "EBAY-GB");
req.Headers.Add("X-EBAY-SOA-REQUEST-DATA-FORMAT", "XML");
req.Headers.Add("X-EBAY-SOA-SECURITY-APPNAME: **********************");
//Set the ContentLength property of the "HttpWebRequest"
req.ContentLength = postDataBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
XDocument myXML = XDocument.Load(resp.GetResponseStream());
IEnumerable<XElement> elements = myXML.Root.Element("searchResult").Elements("item");
I've tried various combinations of the last line - getting the Count of the Descendants for example, but always ge开发者_开发知识库t variations of 'no matching elements' messages. I know that the results are there: when I set a breakpoint and look at the myXML variable in Visual Studio, the XML all seems to be in the Root.
The problem is that the returned XML uses XML namespaces, while your query doesn't. Assuming the namespace is the same as the one in the XML you are sending to the server, this would work:
XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services";
var elements = myXML.Root.Element(ns + "searchResult").Elements(ns + "item");
精彩评论