解析eBay's api result xml时没有找到任何元素

本文关键字:元素 任何 xml result eBay api 解析 | 更新日期: 2023-09-27 18:01:42

我正在尝试通过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似乎都在根目录中。

解析eBay's api result xml时没有找到任何元素

问题是返回的XML使用XML名称空间,而您的查询没有。假设该名称空间与您发送给服务器的XML中的名称空间相同,则可以这样做:

XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services";
var elements = myXML.Root.Element(ns + "searchResult").Elements(ns + "item");