【问题标题】:How to convert XMLDocument type to string in order to show the result in a label如何将 XMLDocument 类型转换为字符串以便在标签中显示结果
【发布时间】:2014-09-19 04:33:08
【问题描述】:

我正在尝试在我的网站上显示来自 World Weather Online 的天气信息。我正在使用 VS2012 和 c# 来创建它。

我可以将在线世界天气中的数据检索到 XMLDocument 类型变量“WP_XMLdoc”下的函数中。

看看下面的代码:

public static XmlDocument WeatherAPI(string sLocation)
{
    HttpWebRequest WP_Request;
    HttpWebResponse WP_Response = null;
    XmlDocument WP_XMLdoc = null;
    String Value;

    string sKey = "xxxxxxxxxxxxxxxxxxxxxxxxx"; //The API key generated by World Weather Online
    string sRequestUrl = "http://api.worldweatheronline.com/free/v1/weather.ashx?format=xml&"; //The request URL for XML format

    try
    {
        //Here we are concatenating the parameters
        WP_Request = (HttpWebRequest)WebRequest.Create(string.Format(sRequestUrl + "q=" + sLocation + "&key=" + sKey));
        WP_Request.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4";
        //Making the request
        WP_Response = (HttpWebResponse)WP_Request.GetResponse();
        WP_XMLdoc = new XmlDocument();
        //Assigning the response to our XML object
        WP_XMLdoc.Load(WP_Response.GetResponseStream());
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    WP_Response.Close();
    return WP_XMLdoc;

    }

}

所以,现在我只想从“WP_XMLdoc”变量中获取 XML 数据,并在我的标签中显示一些细节,例如 temp_c、风速、时间等。 我该怎么做?

“WP_XMLdoc”下的 XML 数据如下:

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <request>
        <type>City</type>
        <query>London, United Kingdom</query>
    </request>
    <current_condition>
        <observation_time>04:17 AM</observation_time>
        <temp_C>17</temp_C>
        <temp_F>63</temp_F>
        <weatherCode>143</weatherCode>
        <weatherIconUrl>
            <![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0006_mist.png]]>
        </weatherIconUrl>
        <weatherDesc>
            <![CDATA[Mist]]>
        </weatherDesc>
        <windspeedMiles>0</windspeedMiles>
        <windspeedKmph>0</windspeedKmph>
        <winddirDegree>62</winddirDegree>
        <winddir16Point>ENE</winddir16Point>
        <precipMM>0.0</precipMM>
        <humidity>94</humidity>
        <visibility>2</visibility>
        <pressure>1010</pressure>
        <cloudcover>50</cloudcover>
    </current_condition>
    <weather>
        <date>2014-09-19</date>
        <tempMaxC>28</tempMaxC>
        <tempMaxF>82</tempMaxF>
        <tempMinC>14</tempMinC>
        <tempMinF>57</tempMinF>
        <windspeedMiles>5</windspeedMiles>
        <windspeedKmph>8</windspeedKmph>
        <winddirection>SSE</winddirection>
        <winddir16Point>SSE</winddir16Point>
        <winddirDegree>149</winddirDegree>
        <weatherCode>356</weatherCode>
        <weatherIconUrl>
            <![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0010_heavy_rain_showers.png]]>
        </weatherIconUrl>
        <weatherDesc>
            <![CDATA[Moderate or heavy rain shower]]>
        </weatherDesc>
        <precipMM>8.3</precipMM>
    </weather>
</data>

请帮忙!

【问题讨论】:

  • 您想如何在标签中显示它?只是在每个节点中转储您的 XML 或值?
  • 如果你看一下xml代码。我只想在屏幕上显示一些信息,例如 /data/current_condition/temp_c、/data/current_condition/windspeedKmph、/data/current_condition/cloudcover 等。

标签: c# asp.net xmldocument weather-api


【解决方案1】:

假设您现有的代码成功地将 XML 数据加载到 XmlDocument 对象,然后我们可以使用 SelectSingleNode() 传递合适的 XPath 表达式作为参数来获取 XML 文档的任何特定部分。比如获取&lt;temp_C&gt;值:

string temp_c = WP_XMLdoc.SelectSingleNode("/data/current_condition/temp_C")
                         .InnerText;

另一种选择是使用更新的 XML API,XDocument。它有Load() 方法,功能类似于XmlDocument.Load()

XDocument WP_XMLdoc = XDocument.Load(WP_Response.GetResponseStream());

使用这种方法,我们可以简单地将XElement 转换为string 以获得它的价值:

string temp_c = (string)WP_XMLdoc.XPathSelectElement("/data/current_condition/temp_C");

【讨论】:

    【解决方案2】:

    试试这样的,例如:

    var str = @"<your xml here>";
    XDocument xdoc = XDocument.Parse(str);
    var output = new List<string>();
    
    foreach (var element in xdoc.Element("data").Element("current_condition").Elements())
    {
        output.Add(string.Format("{0} : {1}",element.Name, element.Value.ToString()));
    }
    

    这将遍历 current_condition 节点的属性,您可以根据需要进行调整以提取您需要的内容。

    【讨论】:

    • xml 值位于 WP_XMLdoc 下。有什么方法可以从中获取值或将 WP_XMLdoc 转换为字符串并从中获取所需的值并显示在标签中?
    【解决方案3】:

    好的,根据您在 cmets 中的回答,我认为您需要显示多列数据。

    最好的选择是使用 GridView 通过 ADO.net 填充您的 XML 数据。这有点容易。

    看看this SO thread

    【讨论】:

    • 不,不是那样......我只想显示从 XML 到所需标签的几个值。我想要这样的: lblTemp.Text = XMLDoc.GetElementsByTagName.temp_c lblwind.Text = XMLDoc.GetElementsByTagName.windspeed_kmph
    猜你喜欢
    • 1970-01-01
    • 2011-01-25
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 2019-06-14
    相关资源
    最近更新 更多