C# 如何在 xml 文档中只显示一个条目?

C# how to show only one entry in a xml document?

我的代码有问题:我只想显示从 http://openweathermap.org/

返回的 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();
                }
            }
        }
    }
}

`

尝试将您的 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

您可以使用 XPath 查询 select temperature 节点,然后获取 value 元素的值。

XmlNode node = xml_document.DocumentElement.SelectSingleNode("/current/temperature");
string current_temperature = node.Attributes.GetNamedItem("value").Value;