2011-10-28 29 views
1

我有這樣的XML:如何從XML獲取此vaue?

<meteo_italia> 
    <localita> 
     <id>2861</id> 
     <nome>Foppolo</nome> 
     <prov>BG</prov> 
     <capoluogo>0</capoluogo> 
     <regione>LOMBARDIA</regione> 
     <previsione time="2011-10-28T06:00"> 
      <id_tempo>6</id_tempo> 
      <desc_tempo>temporali isolati</desc_tempo> 
      <temp>2</temp> 
      <press>1024.3</press> 
      <um_rel>78</um_rel> 
      <zerot>3000 m</zerot> 
      <qn>ND</qn> 
      <v_dir>ESE</v_dir> 
      <v_int>4 nodi</v_int> 
      <ore_s>3</ore_s> 
      <prec>0-10mm</prec> 
     </previsione> 
     <previsione time="2011-10-28T12:00"> 
      <id_tempo>6</id_tempo> 
      <desc_tempo>temporali isolati</desc_tempo> 
      <temp>11</temp> 
      <press>1024.9</press> 
      <um_rel>46</um_rel> 
      <zerot>3550 m</zerot> 
      <qn>ND</qn> 
      <v_dir>SSO</v_dir> 
      <v_int>3 nodi</v_int> 
      <ore_s>3</ore_s> 
      <prec>0-10mm</prec> 
     </previsione> 

     ... XML continues... 

,我想從C#中的第二個節點previsione提取價值temp

試圖用:

using (var wc = new WebClient()) 
{ 
    m_strFilePath = wc.DownloadString(xmlMeteo); 
} 

XmlDocument myXmlDocument = new XmlDocument(); 
myXmlDocument.LoadXml(m_strFilePath); 

try 
{ 
    Response.Write("Value : " + myXmlDocument.SelectSingleNode("//previsione[position()=0]//temp").Value); 
} 
catch { } 

,但我不能得到它。

+0

也有效,// previsione [位置()= 2] /溫度 – BLUEPIXY

回答

3

試着改變你的查詢:

"//previsione[2]/temp" 

和訪問.InnerText而非.Valuesince .Value rarely has an actual value,從不爲元素)。

[2]應該(根據要求)取項; /temp表示「子元素temp」。

+0

試過。沒有什麼.. :( – markzzz

+0

@markzzz見編輯; p –

+0

是的,它似乎工作!我用哪種語言來查詢此值?這不是XPath ... – markzzz

1

它看起來像你的XPath字符串是錯誤的 - 雙斜槓(「/」),當你有它得到它是得到一個後裔(http://www.tizag.com/xmlTutorial/xpathdescendant.php)。

嘗試只使用一個斜槓,因爲這隻會讓孩子。

//previsione[2]/temp 

而且 - XSLT元素不是從零開始的,所以元素在pos開始= 1

這裏是一個網站,我覺得很適合讓XPATH字符串它還格式化XML太偉大! !

http://xmltoolbox.appspot.com/index.html

+0

它不工作的... – markzzz

+0

見編輯 - 抱歉,我錯過了閱讀部分說你想要的第二個元素! 感謝@Marc Gravell指出了這一點! –

1

的XPath的節點現在的位置是立足於1,不是0。請嘗試:

myXmlDocument.SelectSingleNode("//previsione[2]/temp/text()").Value;