0

I'm trying to parse the below XML data to get the values of Name and Total for each MetricResponse

<MetricResponses xmlns="http://schemas.microsoft.com/windowsazure" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
  <MetricResponse>
    <Code>Success</Code>
    <Data>
       <DisplayName>CPU Time</DisplayName>
       <EndTime>2013-04-16T17:10:37.6101155Z</EndTime>
       <Name>CpuTime</Name>
       <PrimaryAggregationType>Total</PrimaryAggregationType>
       <StartTime>2013-04-16T17:00:00Z</StartTime>
       <TimeGrain>PT1H</TimeGrain>
       <Unit>Milliseconds</Unit>
       <Values>
         <MetricSample>
           <Count>1</Count>
           <Maximum i:nil="true" />
           <Minimum i:nil="true" />
           <TimeCreated>2013-04-16T17:00:00Z</TimeCreated>
           <Total>390</Total>
       </MetricSample>
     </Values>
  </Data>
<Message />
</MetricResponse>

I have written the following LINQ query for it:

  XNamespace ns = "http://schemas.microsoft.com/windowsazure";
  var metrics = from b in doc.Root.Descendants(ns + "MetricResponse")
                select new
                {
                    name=b.Element(ns+"Data").Element(ns+"Name"),
                    total=b.Element(ns+"Data").Element(ns+"Values").Element(ns+"MetricSample").Element(ns+"Total")
                };

But when I get a NullReferenceException when I am looping through metrics. The query works fine for getting the Name value and the exception occurs for Total expression.

Matthew Haugen
  • 12,916
  • 5
  • 38
  • 54
Sridhar
  • 837
  • 1
  • 10
  • 21
  • Maybe some `` elements doesn't have `` descendant element, can you verify this? – har07 Oct 05 '14 at 08:28
  • All `` elements have a `` element under . This is the XML data. http://msdn.microsoft.com/en-us/library/azure/dn166964.aspx – Sridhar Oct 05 '14 at 08:30
  • 1
    Yes, but your code doesn't throw exception given XML from that MSDN link : https://dotnetfiddle.net/V4EqPU – har07 Oct 05 '14 at 08:40
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Matthew Haugen Oct 05 '14 at 09:15

0 Answers0