0

Hey guys I'm trying to get some values from a deeper container in my xdocument but i always run in an Nullreference.

This is my code so far:

                StreamReader xmlStream = new StreamReader(rsp.GetResponseStream());
            string XMLstr = xmlStream.ReadToEnd();
            XDocument xelement = XDocument.Parse(XMLstr);
            xmlStream.Close();


            IEnumerable<XElement> items = xelement.Elements();

            foreach (var item in items )
            {
                Console.WriteLine(item.Element("ItemID").Value.ToString());
            }

This is the XML I want to work with:

    <GetSellerListResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2016-02-26T22:02:38.968Z</Timestamp>
  <Ack>Success</Ack>
  <Version>967</Version>
  <Build>967_CORE_BUNDLED_10708779_R1</Build>
  <PaginationResult>
    <TotalNumberOfPages>14</TotalNumberOfPages>
    <TotalNumberOfEntries>27</TotalNumberOfEntries>
  </PaginationResult>
  <HasMoreItems>true</HasMoreItems>
  <ItemArray>
    <Item>
      <AutoPay>false</AutoPay>
      <BuyerProtection>ItemIneligible</BuyerProtection>
      <Country>US</Country>
      <Currency>USD</Currency>
      <HitCounter>NoHitCounter</HitCounter>
      <ItemID>110043597553</ItemID>
      <ListingDetails>
        <StartTime>2016-02-12T23:35:27.000Z</StartTime>
        <EndTime>2016-02-19T23:35:27.000Z</EndTime>
        <ViewItemURL>http://cgi.sandbox.ebay.com/ws/eBayISAPI.dll?ViewItem&
           item=110043597553&category=41393</ViewItemURL>
        <HasUnansweredQuestions>false</HasUnansweredQuestions>
        <HasPublicMessages>false</HasPublicMessages>
        <BuyItNowAvailable>true</BuyItNowAvailable>
      </ListingDetails>
      <ListingDuration>Days_7</ListingDuration>
      <Location>Santa Cruz, California</Location>
      <PrimaryCategory>
        <CategoryID>41393</CategoryID>
        <CategoryName>Collectibles:Decorative Collectibles:Other</CategoryName>
      </PrimaryCategory>
      <Quantity>1</Quantity>
      <ReviseStatus>
        <ItemRevised>false</ItemRevised>
      </ReviseStatus>
      <SecondaryCategory>
        <CategoryID>95116</CategoryID>
        <CategoryName>Collectibles:Disneyana:Contemporary (1968-Now):Bobblehead Figures</CategoryName>
      </SecondaryCategory>
      <SellingStatus>
        <BidCount>0</BidCount>
        <BidIncrement currencyID="USD">0.5</BidIncrement>
        <ConvertedCurrentPrice currencyID="USD">11.49</ConvertedCurrentPrice>
        <CurrentPrice currencyID="USD">11.49</CurrentPrice>
        <MinimumToBid currencyID="USD">11.49</MinimumToBid>
        <QuantitySold>0</QuantitySold>
        <SecondChanceEligible>false</SecondChanceEligible>
        <ListingStatus>Completed</ListingStatus>
      </SellingStatus>
      <ShipToLocations>US</ShipToLocations>
      <Site>US</Site>
      <Storefront>
        <StoreCategoryID>1</StoreCategoryID>
        <StoreCategory2ID>0</StoreCategory2ID>
        <StoreURL>http://www.stores.sandbox.ebay.com/id=132854966</StoreURL>
      </Storefront>
      <SubTitle>Micky, with the ears!</SubTitle>
      <TimeLeft>PT0S</TimeLeft>
      <Title>Kelly's Kitsch</Title>
      <WatchCount>0</WatchCount>
      <PostalCode>95062</PostalCode>
      <PictureDetails>
        <GalleryURL>http://thumbs.ebaystatic.com/pict/41007087008080_0.jpg</GalleryURL>
        <PhotoDisplay>None</PhotoDisplay>
        <PictureURL>http://thumbs.ebaystatic.com/pict/41007087008080_0.jpg</PictureURL>
      </PictureDetails>
      <ProxyItem>false</ProxyItem>
      <ReturnPolicy>
        <RefundOption>MoneyBack</RefundOption>
        <Refund>Money Back</Refund>
        <ReturnsWithinOption>Days_30</ReturnsWithinOption>
        <ReturnsWithin>30 Days</ReturnsWithin>
        <ReturnsAcceptedOption>ReturnsAccepted</ReturnsAcceptedOption>
        <ReturnsAccepted>Returns Accepted</ReturnsAccepted>
        <Description>Returns accepted only if item is not as described.</Description>
        <ShippingCostPaidByOption>Buyer</ShippingCostPaidByOption>
        <ShippingCostPaidBy>Buyer</ShippingCostPaidBy>
      </ReturnPolicy>
      <PaymentAllowedSite>US</PaymentAllowedSite>
    </Item>
   </ItemArray>
  <ItemsPerPage>2</ItemsPerPage>
  <PageNumber>1</PageNumber>
  <ReturnedItemCountActual>2</ReturnedItemCountActual>
</GetSellerListResponse>

Can anybody please explain what I am missing?

Thanks

josef_skywalker
  • 1,047
  • 1
  • 9
  • 16

2 Answers2

1

You're calling Elements() on the XDocument, so that's just going to return the root element.

You're then calling Element("ItemID") on that root element - asking for an element which doesn't exist. So that will return null, leading to your exception. Additionally, you're ignoring the fact that all your elements are in a namespace.

It looks like you probably actually want the Item elements, so you could just use:

// Changed the variable name to match what it is...
XDocument doc = XDocument.Parse(XMLstr);
XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
Enumerable<XElement> items = doc.Descendants(ns + "Item");
foreach (var item in items)
{
    // XElement.Value is already a string; no need to call ToString on it
    Console.WriteLine(item.Element(ns + "ItemID").Value);
}

An alternative would be to specifically find the ItemArray element, and its Item children:

XDocument doc = XDocument.Parse(XMLstr);
XNamespace ns = "urn:ebay:apis:eBLBaseComponents";
Enumerable<XElement> items = doc.Root
                                .Element(ns + "ItemArray")
                                .Elements(ns + "Item");
// Code as before
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • You are right. I have tried so much I have messed up the code completly. I have tried the first code. But it just returns one element. What if there are more "item" containers? – josef_skywalker Jul 21 '16 at 19:48
  • @josef_skywalker: Then it will loop that many times. But the sample XML you've given only has one Item element. – Jon Skeet Jul 21 '16 at 19:52
0

To any VB user that finds this. First thing is to note that there is a namespace so one of the easiest ways to take that into account is to add an Imports statement.

Imports <xmlns="urn:ebay:apis:eBLBaseComponents">

Next parse the response.

Dim someXE As XElement = XElement.Parse(XMLstr)

Then select all of the ItemID's regardless of where they are located

Dim itemID As IEnumerable(Of XElement) = someXE...<ItemID>

and finally to look at them individually

For Each id As XElement In itemID
    Debug.WriteLine(id.Value) 'from example above 110043597553
Next
dbasnett
  • 11,334
  • 2
  • 25
  • 33