C# C如何在xml文档中只显示一个条目?
我的代码有一个问题:我只想显示从XML返回的温度 `尝试将GetFormattedXml更新为以下内容:C# C如何在xml文档中只显示一个条目?,c#,xml,winforms,weather,C#,Xml,Winforms,Weather,我的代码有一个问题:我只想显示从XML返回的温度 `尝试将GetFormattedXml更新为以下内容: private string GetFormattedXml(string url) { // Create a web client. using (WebClient client = new WebClient()) { // Get the response string from the URL
private string GetFormattedXml(string url)
{
// Create a web client.
using (WebClient client = new WebClient())
{
// Get the response string from the URL.
string xml = client.DownloadString(url);
// Load the response into an XML document.
XmlDocument xml_document = new XmlDocument();
xml_document.LoadXml(xml);
return xml_document.SelectSingleNode("/current/temperature").Attributes["value"].Value;
}
}
然后您可以将其重命名为GetTemperature,您可以使用XPath查询选择温度节点,然后获取value元素的值
@user7371443如果这解决了您的问题,请将其标记为答案。但是返回类型是string,因此无法返回属性。有什么想法吗?@user7371443从属性中获取值并返回该值。@BrianRogers是的,但是如何:我对c@Tha埃拉尔·阿朱罗尼非常感谢,现在它可以工作了。祝你今天愉快
private string GetFormattedXml(string url)
{
// Create a web client.
using (WebClient client = new WebClient())
{
// Get the response string from the URL.
string xml = client.DownloadString(url);
// Load the response into an XML document.
XmlDocument xml_document = new XmlDocument();
xml_document.LoadXml(xml);
return xml_document.SelectSingleNode("/current/temperature").Attributes["value"].Value;
}
}
XmlNode node = xml_document.DocumentElement.SelectSingleNode("/current/temperature");
string current_temperature = node.Attributes.GetNamedItem("value").Value;