2012-02-10 23 views
1

問題是解析xml文件從<...>到<.../>

我有XML文件這樣的結構

...................... 
<current_conditions> 
    <condition data="partly cloudy"/> 
    <temp_f data="2"/> 
    <temp_c data="-17"/> 
    <humidity data="Huminidy: 66 %"/> 
    <icon data="/ig/images/weather/partly_cloudy.gif"/> 
    <wind_condition data="Wind: С, 2 м/с"/> 
</current_conditions> 
<forecast_conditions> 
    <day_of_week data=""/> 
    <low data="-23"/> 
    <high data="-14"/> 
    <icon data="/ig/images/weather/mostly_sunny.gif"/> 
    <condition data="Mostly sunny"/> 
</forecast_conditions> 
..................... 

我解析它像這樣

   while (r.Read()) 
       { 
        if (r.NodeType == XmlNodeType.Element) 
        { 
         if (r.Name == "current_conditions") 
         { 
          string temp = ""; 
          while (r.Read() && r.Name!="forecast_conditions")//I've addee this condition because it parse all nodes after "current conditions" 
          { 
           if (Current_Condtions.Contains(r.Name)) 
           { 
            temp += r.GetAttribute("data"); 
            temp += "\n"; 
           } 
          } 
          Console.WriteLine(temp); 
         } 
        } 
       } 

我添加條件但它仍然讀取文件到最後,但我只想解析從<current_conditions></current_conditions>,然後停止閱讀xml文件。 如何做到這一點?

+0

你定義一個突破;當你滿足特定的條件,或者您需要重構while循環,並使用一個for循環,如果你知道你正在尋找... – MethodMan 2012-02-10 20:23:39

+1

看看'XDocument'和'XPath'特定計數。 – Oded 2012-02-10 20:25:20

回答

1

最簡單的方法就是你得到你需要的數據後添加break;聲明。

一個清潔的方法是使用ReadSubtree method.使用它,一旦你的current_conditions節點上創建一個新的閱讀器。那麼它只會讀取該節點及其子節點。

喜歡的東西

r.ReadToFollowing("current_conditions") 
subtree = r.ReadSubtree() 
while(subtree.Read()) 
{ 
    //Do your stuff with subtree... 
} 
+0

如何閱讀沒有子樹的所有屬性呢?我的意思是examp不讀'<圖標數據..... />' – 2012-02-10 20:58:18

+0

使用break語句走出while循環。 – 2012-02-10 21:13:46

1

您需要在您做了你想要的東西點break聲明。

相關問題