Search code examples
c#xmlfileweather-api

Reading Specific Values From XML in C#


I have used a weather API to return temperature values in XML format and written them to a text file. My next step is reading the values in from the XML file for use in my program. This is the format the values are in;

<temperature value="21.37" min="18.89" max="22.78" unit="metric">
</temperature>
<humidity value="68" unit="%">
</humidity>
<pressure value="1019" unit="hPa">
</pressure>

I'd like to access the temperature value, but I am unsure how to do that by reading in from the text file especially considering that the text file is a lot longer than what I need. What would be the most efficient way to access the values I want?

EDIT:

<current>
  <city id="" name="">
    <coord lon="-0.45" lat="52.19">
    </coord>
    <country>GB</country>
    <sun rise="2016-08-16T04:48:13" set="2016-08-16T19:22:26">
    </sun>
  </city>
  <temperature value="22.06" min="19.44" max="23.89" unit="metric">
  </temperature>
  <humidity value="67" unit="%">
  </humidity>
  <pressure value="1019" unit="hPa">
  </pressure>
  <wind>
    <speed value="2.57" name="Light breeze">
    </speed>
    <gusts value="6.17">
    </gusts>
    <direction value="73" code="ENE" name="East-northeast">
    </direction>
  </wind>
  <clouds value="24" name="few clouds">
  </clouds>
  <visibility>
  </visibility>
  <precipitation mode="no">
  </precipitation>
  <weather number="801" value="few clouds" icon="02d">
  </weather>
  <lastupdate value="2016-08-16T10:44:02">
  </lastupdate>
</current>

Solution

  • One way can be:

    var result = XDocument.Load("data.xml").Root
                          .Element(/*.... the rest of the hierarchy.. */)
                          .Element("temperature")
                          .Attribute("value").Value;
    

    If you don't want to specify the entire way to the element you can:

    var result = XDocument.Load("data.xml").Root
                          .Descendants("temperature")
                          .Select(element => element.Attribute("value").Value).FirstOrDefault();