阅读XML内容

时间:2017-08-17 17:24:18

标签: c# xml xmldocument

假设我有一个XML:

<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>

我能够在变量&#34; test&#34;中看到City和Wind的信息。当像我想要的那样进行调试时,其余的我都会得到空白。我的代码是:

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;
}

我将取代&#34;测试&#34;以后用一个对象。这是retrieveXMLResponse方法:

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;
}

1 个答案:

答案 0 :(得分:3)

节点上没有内部XML只包含属性,因此InnerXML属性为空。如果要读取给定节点的属性值,则每个XML节点都具有attributes属性。