1

It's been a while since I have worked with ASP.Net and C#. I am trying to parse an XML API using C# and I am in need of some help. My Problem is I am not quite sure how to do this. I keep seeing conflicting methods too. Some show like I did below. Some show pretty awesome queries that to me look way more better.

Example of query

IEnumerable<string> partNos =
    from item in purchaseOrder.Descendants("Item")
    select (string) item.Attribute("PartNumber");

Which method is better and how do I achieve parsing the XML just to a textbox for now?

Here is the XML format: This XML file does not appear to have any style information associated with it. The document tree is shown below.

<findItemsByKeywordsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services">
<ack>Success</ack>
<version>1.12.0</version>
<timestamp>2012-06-20T22:20:33.539Z</timestamp>
<searchResult count="1">
<item>
<itemId>390432965446</itemId>
<title>
Yamaha RX-V673 7.2 Channel 90 Watt Aventage Receiver {Brand New}
</title>
<globalId>EBAY-US</globalId>
<primaryCategory>
<categoryId>14981</categoryId>
<categoryName>Home Theater Receivers</categoryName>
</primaryCategory>
<galleryURL>
http://thumbs3.ebaystatic.com/pict/3904329654464040_1.jpg
</galleryURL>
<viewItemURL>
http://www.ebay.com/itm/Yamaha-RX-V673-7-2-Channel-90-Watt-Aventage-Receiver-Brand-New-/390432965446?pt=Receivers_Tuners
</viewItemURL>
<productId type="ReferenceID">114468754</productId>
<paymentMethod>PayPal</paymentMethod>
<autoPay>false</autoPay>
<postalCode>54143</postalCode>
<location>Marinette,WI,USA</location>
<country>US</country>
<shippingInfo>
<shippingServiceCost currencyId="USD">0.0</shippingServiceCost>
<shippingType>Free</shippingType>
<shipToLocations>US</shipToLocations>
<expeditedShipping>false</expeditedShipping>
<oneDayShippingAvailable>false</oneDayShippingAvailable>
<handlingTime>2</handlingTime>
</shippingInfo>
<sellingStatus>
<currentPrice currencyId="USD">519.0</currentPrice>
<convertedCurrentPrice currencyId="USD">519.0</convertedCurrentPrice>
<sellingState>Active</sellingState>
<timeLeft>P28DT23H32M35S</timeLeft>
</sellingStatus>
<listingInfo>
<bestOfferEnabled>false</bestOfferEnabled>
<buyItNowAvailable>false</buyItNowAvailable>
<startTime>2012-06-19T21:48:08.000Z</startTime>
<endTime>2012-07-19T21:53:08.000Z</endTime>
<listingType>StoreInventory</listingType>
<gift>false</gift>
</listingInfo>
<returnsAccepted>true</returnsAccepted>
<condition>
<conditionId>1000</conditionId>
<conditionDisplayName>New</conditionDisplayName>
</condition>
<isMultiVariationListing>false</isMultiVariationListing>
</item>
</searchResult>
<paginationOutput>
<pageNumber>1</pageNumber>
<entriesPerPage>1</entriesPerPage>
<totalPages>1121495</totalPages>
<totalEntries>1121495</totalEntries>
</paginationOutput>
<itemSearchURL>
http://www.ebay.com/sch/i.html?_nkw=yamaha&_ddo=1&_ipg=1&_pgn=1
</itemSearchURL>
</findItemsByKeywordsResponse>

My C# Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

namespace ebayLinq
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string myAppID = "hidden from stack overflow";
            string ebayUrl = "http://svcs.ebay.com/services/search/FindingService/v1?";
            string operationName = "OPERATION-NAME=getSearchKeywordsRecommendation&";
            string serviceVersion = "SERVICE-VERSION=1.11.0&";
            string securityAppName = "SECURITY-APPNAME="+ myAppID +"&";
            string responseData = "RESPONSE-DATA-FORMAT=XML&";
            string rest = "REST-PAYLOAD&";

            string searchString = "macbook Pro";
            string keywords ="keywords="+searchString+"&";


            var xml = XDocument.Load(ebayUrl + 
                                        operationName + 
                                        serviceVersion + 
                                        securityAppName + 
                                        responseData);

            //XNamespace ns = "http://www.ebay.com/marketplace/search/v1/services";
            //XElement ack = xml.Root.Element(ns + "ack");    
        }
    }
}

Okay so as you can I can get it to work with the code above, but I dont know how to go deeper than the ack so far. I also would rather do queries as opposed to the method used above.

Any input friends?

With your input I came up with this but it doesn't work right?

   XElement convertedCurrentPrice = (from x in xml.Root.Descendants("title") select x).FirstOrDefault();
                string item = Convert.ToString(convertedCurrentPrice);
                TextBox1.Text = item;
allencoded
  • 7,015
  • 17
  • 72
  • 126
  • Thats not gonna work. convertedCurrentPrice is an XElement and to my knowledge you can't just call .ToString on the element itself. Try this: string item = convertedCurrentPrice.Value; TextBox1.Text = item; – Jesse Carter Jun 20 '12 at 23:25

2 Answers2

1

It's hard to answer which syntax is better. For reference, they are called Query Syntax and Method Syntax. Here is a the MSDN article on the differences (the article recommends query syntax due to readability). They are roughly equivalent, and I use both of them frequently.

For further reference, here is an SO question discussing the topic.

Community
  • 1
  • 1
Kyeotic
  • 19,697
  • 10
  • 71
  • 128
1

I'm not personally familiar with older methods of parsing XML but the new LINQ to XML stuff is the query style that you are talking about and definitely makes things quick and easy when it comes to pulling information out of your XDocument.

If you give me an example of one or more of the nodes that you want to pull data from in particular I can help you out with that but the basic structure would be (say if you wanted to grab the current price value of 519.0)

XElement convertedCurrentPrice = (from x in xml.Root.Descendants("convertedCurrentPrice") select x).FirstOrDefault();

This will return the entire XML node (everything in between and

Then getting the value is as simple as:

double price = Convert.ToDecimal(convertedCurrentPrice.Value);
Jesse Carter
  • 20,062
  • 7
  • 64
  • 101
  • Now that I think about it I'm pretty sure this can be combined into one line as well. I'll get back to you with that. – Jesse Carter Jun 20 '12 at 22:46
  • I can help you with syntax if you're looking on getting specific node values. This is a pretty simple XDocument as there doesn't appear to be a lot of nested elements. Also, feel free to upvote or mark as answer if you you find this helpful :) – Jesse Carter Jun 20 '12 at 22:53
  • Actually I tried a bit of something with your code and it doesn't seem to work. It runs but textbox1 doesn't show anything inside of it. I will edit my response and post my code at the very bottom. See if you realize something i dont. – allencoded Jun 20 '12 at 23:03