Share via


Building Objects from XML of eBay API with LINQ

In this post, I’d like to illustrate the power of LINQ with code sample. I query the web service published by eBay. Refer to this article about eBay API concepts.

 

EbayItem.cs

namespace LINQ2EbayResponse

{

    class EbayItem

    {

        public string ItemID { get; set; }

        public string Title { get; set; }

    }

}

Program.cs

namespace LINQ2EbayResponse

{

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Xml.Linq;

class Demo

    {

        static void Main(string[] args)

        {

            const string myAppID = @"Microsof-e148-4fe7-840c-38a19f6d59ba";

            const string queryString = @"ipod";

            Demo demo = new Demo();

            demo.MakePOXCall(myAppID, queryString);

            Console.WriteLine("End.");

        }

        private void MakePOXCall(string appID, string queryString)

        {

            // Make the call to eBay & Retrieve response XML to objects

            string eBayUrl = string.Format(@"https://open.api.ebay.com/shopping?appid={0}&version=517&siteid=0&callname=FindItems&QueryKeywords={1}&responseencoding=xml&callback=false", appID, queryString);

            WebClient ebayService = new WebClient();

            string ebayResponse = ebayService.DownloadString(new Uri(eBayUrl));

           XNamespace ebayNamespace = "urn:ebay:apis:eBLBaseComponents";

            XElement xmlItems = XElement.Parse(ebayResponse);

            var items = from Item in xmlItems.Elements(ebayNamespace + "Item")

                        select new EbayItem

                        {

                            ItemID = (string)Item.Element(ebayNamespace + "ItemID"),

                            Title = (string)Item.Element(ebayNamespace + "Title")

           };

            foreach (EbayItem item in items)

            {

                Console.WriteLine("ItemID: " + item.ItemID + ", Title: " + item.Title);

            }

        }

    }

}

Done! in-memory objects are built. You can also follow ScottGu’s blog to wire up this code with Silverlight UI.

Comments