Search code examples
c#xmlxmldocument

Read XML content


Suppose I have an XML like:

<current>
  <city id="2563232" name="London">
    <coord lon="-0.13" lat="51.51">
    <country>GB</country>
    <sun rise="2017-08-17T04:23:00" set="2017-08-17T17:48:39"/>
  </city>
  <temperature value="305.15" min="305.15" max="305.15" unit="kelvin"/>
  <humidity value="25" unit="%"/>
  <pressure value="1015" unit="hPa"/>
  <wind>...</wind>
  <clouds value="0" name="clear sky"/>
  <visibility value="10000"/>
</current>

I am able to see the info for City and Wind in my variable "test" when debugging like i want, but I get blanks for the rest. My code is:

XmlNodeList xnlNodes = OtherClass.retrieveXMLResponse(respStream);
String test = "";

foreach (XmlNode xndNode in xnlNodes)
{
  test = xndNode["city"].InnerXml;
  test = xndNode["wind"].InnerXml;
  test = xndNode["temperature"].InnerXml;
  test = xndNode["humidity"].InnerXml;
  test = xndNode["pressure"].InnerXml;
  test = xndNode["clouds"].InnerXml;
  test = xndNode["visibility"].InnerXml;
}

I will be replacing "test" with an object later. This is the retrieveXMLResponse method:

public static XmlNodeList retrieveXMLResponse(Stream stream)
{
    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
    string responseString = reader.ReadToEnd();
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.LoadXml(responseString);

    XmlElement xelRoot = xmlDoc.DocumentElement;
    XmlNodeList xnlNodes = xelRoot.SelectNodes("/current");

    return xnlNodes;
}

Solution

  • There is no inner XML on the nodes that just contain attributes, thus the InnerXML property is blank. Each XML node has an attributes property if you would like to read the attribute values for a given node.