2014-09-19 3 views
2

전 세계 날씨에서 웹 사이트의 날씨 정보를 표시하려고합니다. 나는 이것을 만들기 위해 C#으로 VS2012를 사용하고있다.레이블에 결과를 표시하기 위해 XMLDocument 유형을 문자열로 변환하는 방법

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> 

이 도와주세요! 예를 들어이 같은

+0

: 우리는 단순히 값의 얻을 stringXElement 캐스팅 할 수

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

이 방법을 사용 :이 기능은 XmlDocument.Load() 유사하다 Load() 방법이있다 ? 각 노드에서 XML 또는 값을 덤프하면됩니까? – Sam

+0

xml 코드를 살펴보십시오./data/current_condition/temp_c,/data/current_condition/windspeedKmph,/data/current_condition/cloudcover 등의 화면에 몇 가지 정보 만 표시하려고합니다. –

답변

1

에서보세요, 우리는 다음 XML 문서의 특정 부분을 얻기 위해 인수로 SelectSingleNode() 통과 적합한 XPath 식을 사용할 수 있습니다. 또 다른 옵션은, XDocument을 새로운 XML API를 사용

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

예를 들어, <temp_C> 값을 얻을 수 있습니다. 당신이 레이블을 표시 할 어떻게

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

모두 삭제 해 주셔서 감사합니다 ... :) : 이 같은 몇 가지를 원한다 –

0

시도 뭔가 :

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 노드의 속성을 통과 것입니다, 당신은 당신이 필요 추출하기 위해 필요에 따라 조정할 수 있습니다.

+0

xml 값은 WP_XMLdoc 아래에 있습니다. 거기에서 가치를 취하거나 WP_XMLdoc을 문자열로 변환하고 원하는 값을 가져 와서 레이블에 표시 할 수있는 방법이 있습니까 ?? –

0

의견에 대한 답변에 따르면, 필자는 데이터 열을 여러 개 표시해야한다고 생각합니다.

가장 좋은 옵션은 GridView을 사용하여 XML 데이터를 ADO.net을 사용하여 채우는 것입니다. 조금 쉬워.

기존 코드가 성공적으로 XmlDocument 객체에 XML 데이터를로드한다고 가정 this SO thread

+0

그럴만 한 것은 아닙니다 .... 저는 XML에서 원하는 레이블로 몇 가지 값만 표시하려고합니다. lblTemp.Text = XMLDoc.GetElementsByTagName.temp_c lblwind.Text = XMLDoc.GetElementsByTagName.windspeed_kmph –

관련 문제