【问题标题】:Get value of child node in xml获取xml中子节点的值
【发布时间】:2020-06-13 11:21:59
【问题描述】:

我在我的 c# WindowsForm 天气 api 中使用它返回我想要从中获取节点的 xml 文件。

<current>
     <city id="2988507" name="Paris">
      <coord lon="2.35" lat="48.85"/>
       <country>FR</country>
       <timezone>7200</timezone>
       <sun rise="2020-06-13T03:46:45" set="2020-06-13T19:54:52"/>
     </city>
     <temperature value="67.41" min="66.2" max="69.01" unit="fahrenheit"/>
     <feels_like value="64.31" unit="fahrenheit"/>
     <humidity value="59" unit="%"/>
     <pressure value="1009" unit="hPa"/>
    </current>

如果我尝试获取温度和城市的值,我没有问题,但是当我尝试获取国家/地区的值时,我得到空错误。

using (WebClient web = new WebClient())
{
     string url = web.DownloadString("http://api.openweathermap.org/data/2.5/weather?q=" + lookedCity + "&mode=xml&units="+tempType+"&appid=70e1d7c5");

     XmlDocument doc = new XmlDocument();
     doc.LoadXml(url);

     temp = doc.DocumentElement.SelectSingleNode("temperature").Attributes["value"].Value;
     country = doc.DocumentElement.SelectSingleNode("country").Value;
     city = doc.DocumentElement.SelectSingleNode("city").Attributes["name"].Value;
}

【问题讨论】:

  • 您试图从根元素中获取country - 但它不是,它在city 中。 (如果您格式化了 XML,这将更容易判断。)因此切换顺序以首先获取 city,然后使用 city.SelectSingleNode("country")。虽然我个人会使用 LINQ to XML,这会使 IMO 更简洁。

标签: c# xml


【解决方案1】:

基本上你需要使用InnerText 而不是Value 并且国家在城市之下。

var country = doc.DocumentElement.SelectSingleNode("city").SelectSingleNode("country").InnerText;

这适用于您的情况,但我建议您使用 linq。

【讨论】:

    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2013-03-19
    • 2013-08-10
    相关资源
    最近更新 更多