2017-01-03 2 views
2

У меня есть проблема с моим кодом: Я хочу только, чтобы показать температуру от XML вернулся из http://openweathermap.org/C# как показать только одну запись в XML-документе?

namespace SMirror 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      lblWeather.Text = GetFormattedXml(CurrentUrl); 
     } 

     private const string API_KEY = "8b1ed1ebf1481ecf201d05b2feeca87d"; 
     private const string CurrentUrl = 
      "http://api.openweathermap.org/data/2.5/weather?" + 
      "q=Berlin&mode=xml&units=imperial&APPID=" + API_KEY; 
     private const string ForecastUrl = 
      "http://api.openweathermap.org/data/2.5/forecast?" + 
      "q=Berlin&mode=xml&units=imperial&APPID=" + API_KEY; 

     // Return the XML result of 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); 

       // Format the XML. 
       using (StringWriter string_writer = new StringWriter()) 
       { 
        XmlTextWriter xml_text_writer = 
        new XmlTextWriter(string_writer); 
        xml_text_writer.Formatting = Formatting.Indented; 
        xml_document.WriteTo(xml_text_writer); 

        // Return the result. 
        return string_writer.ToString(); 
       } 
      } 
     } 
    } 
} 

`

ответ

1

Попробуйте обновить свой GetFormattedXml быть следующим:

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

+0

@ user7371443 Если это исправить вашу проблему, то любезно пометьте ее как ответ. –

+0

Но возвращаемый тип - строка, поэтому он не может вернуть атрибут. Есть идеи ? –

+0

@ user7371443 Получите «Значение» из атрибута и верните его. –

0

Вы можете использовать XPath que ry, чтобы выбрать узел temperature, а затем получить значение элемента value.

XmlNode node = xml_document.DocumentElement.SelectSingleNode("/current/temperature"); 
string current_temperature = node.Attributes.GetNamedItem("value").Value; 
Смежные вопросы