0

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

4

1 回答 1

0

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

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

var elements = myXML.Root.Element(ns + "searchResult").Elements(ns + "item");
于 2011-07-09T15:11:02.487 回答