2012-02-10 68 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声明。

相关问题