Parsing xml in c#

Let's assume we have XML structure like following :

<current>
<city id="587084" name="Baku">
<coord lon="49.89" lat="40.38"/>
<country>AZ</country>
<sun rise="2017-11-24T03:37:06" set="2017-11-24T13:17:07"/>
</city>
<temperature value="282.15" min="282.15" max="282.15" unit="kelvin"/>
<humidity value="81" unit="%"/>
<pressure value="1018" unit="hPa"/>
<wind>
<speed value="7.7" name="Moderate breeze"/>
<gusts/>
<direction value="320" code="NW" name="Northwest"/>
</wind>
<clouds value="90" name="overcast clouds"/>
<visibility value="10000"/>
<precipitation mode="no"/>
<weather number="804" value="overcast clouds" icon="04d"/>
<lastupdate value="2017-11-24T10:30:00"/>
</current>

If we need to take temperature value from this XML file, we can use LINQ :

   string result = "";
            var xdoc = XDocument.Load(URL);
            var entries = from e in xdoc.Descendants("temperature")
                          select new
                          {
                              Id = (string)e.Attribute("value").Value,
                              Unit = (string)e.Attribute("unit").Value
                          };
            foreach (var entry in entries)
            {
                result = result + " " + (entry.Id);
            }


Reference : https://stackoverflow.com/questions/670563/linq-to-read-xml

Comments

Popular posts from this blog