T.Rhodes
T.Rhodes

Reputation: 157

trouble getting attributes from XML elements using LINQ

So I am parsing out attributes and values from some XML returned from a third party API and I am getting inconsistent results. The XML looks like this:

<propertyMetrics month="12" year="2013" propertyId="3923837">
  <metric name="siteTotal" uom="kBtu" dataType="numeric">
    <value>409249.0</value>
  </metric>
  <metric name="waterUseTotal" uom="kgal" dataType="numeric">
    <value>2434.2</value>
  </metric>
  <metric name="totalGHGEmissions" uom="MtCO2e" dataType="numeric">
    <value>28.5</value>
  </metric>
  <metric name="greenPowerOnSite" dataType="numeric">
    <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true" />
  </metric>
</propertyMetrics>

I use the following code in LINQPad to query the XML:

var propMetrics = doc.Descendants("metric").Attributes();

My output from LINQpad looks like this:

IEnumerable<XAttribute> (11 items) 
name="siteTotal" 
dataType="numeric" 
name="waterUseTotal" 
dataType="numeric" 
name="totalGHGEmissions" 
uom="MtCO2e" 
dataType="numeric" 
name="greenPowerOnSite" 
dataType="numeric" 

As you can see it is not capturing all the attributes, most notably it only has one uom attribute. Does anyone know why this might be happening? Thanks!

Upvotes: 0

Views: 88

Answers (1)

Farhad Alizadeh Noori
Farhad Alizadeh Noori

Reputation: 2306

I just used LINQPad and am getting the correct result using:

propMetrics.Descendants("metric").Attributes()

The only thing that I think could be happening here is some encoding problems in the string returned from the third party API. Try copying the xml from you question to LINQPad and testing to confirm this.

Upvotes: 1

Related Questions