Artem Tsarionov
Artem Tsarionov

Reputation: 329

parse xml file from <...> to <.../>

The problem is

I've got xml file with such structure

......................
<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>
.....................

I parse it like this

               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);
                        }
                    }
                }

I've added conditions but It still read file to the end, but I only want to parse from <current_conditions> to </current_conditions> and then stop reading xml file. How to do it?

Upvotes: 1

Views: 198

Answers (3)

Chriseyre2000
Chriseyre2000

Reputation: 2053

Try using the innerXML attribute.

Upvotes: 0

Antony Scott
Antony Scott

Reputation: 22006

you need a break statement at the point where you've done what you wanted.

Upvotes: 1

Kris Harper
Kris Harper

Reputation: 5862

The easiest way is to add a break; statement after you get the data you need.

A cleaner way would be to use the ReadSubtree method. Use it to create a new reader once you're on the current_conditions node. Then it will only read that node and its children.

Something like

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

Upvotes: 1

Related Questions