解析eBay的api结果xml时找不到任何元素

时间:2011-07-09 10:41:28

标签: c# xml ebay-api

我正在尝试通过C#和XML搜索eBay。我可以看到我通过将XML写入字符串来获得有效的XML响应,但无法使用C#解析它 - 我只是不断被告知没有元素。

这是我的代码,删除了我的appname键:

   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");

我尝试了最后一行的各种组合 - 例如获得后代的计数,但总是得到'无匹配元素'消息的变体。我知道结果是存在的:当我设置断点并查看Visual Studio中的myXML变量时,XML似乎都在Root中。

1 个答案:

答案 0 :(得分:0)

问题是返回的XML使用XML命名空间,而查询却没有。假设命名空间与您发送给服务器的XML中的命名空间相同,这将起作用:

XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services";

var elements = myXML.Root.Element(ns + "searchResult").Elements(ns + "item");