KMC
KMC

Reputation: 20046

Parsing a complexly nested XML

I had been reading various tutorials but couldn't figure out to conditionally parse the following XML structure, where user inputs name of a State and then receive the name of the Capitol.

When I test it with the following code, I get no MessageBox popped up.

C# code

XDocument xd = XDocument.Load("Foo.xml");

foreach (var state in xd.Descendants("State"))
{
      Messagebox.Show(state.Attribute("Name").Value);
}

Foo.xml

<Main>
   <Title></Title>
   <Planet Name="Earth">
      <Continent Name="North America">
         <Country Name="USA">
            <State Name="Illinois" Capital="Springfield"></State>
            <State Name="Alabama" Capital="Montgomery"></State>
            ...
         </Country>
         <Country Name="Canada">
            <State Name="Alberta" Capital="Edmonton"></State>
            <State Name="British Columbia" Capital="Victoria"></State>  
            <State Name="Manitoba" Capital="Winnipeg"></State>
            ....
         </Country>
         <Country> ... </Country>
         <Country> ... </Country>
         <Country> ... </Country>
      </Continent>
   </Planet>
</Main>

Upvotes: 0

Views: 64

Answers (2)

Souvik Ghosh
Souvik Ghosh

Reputation: 4616

I have modified your code a bit. This will return you the capitol from the state.

var stateCapital = from states in XDocument.Load(@"foo.xml").Descendants("State")
                    where states.Attribute("Name").Value == "Alabama"
                    select states.Attribute("Capital").Value;

Messagebox.Show(stateCapital);

If you need the names of all the Capitals for every state in a for loop-

var statesCollection = from states in XDocument.Load(@"foo.xml").Descendants("State") select states;

foreach (var state in statesCollection)
{
    Messagebox.Show(state.Attribute("Capital").Value);
}

Upvotes: 1

Ben
Ben

Reputation: 763

This should work:

List<State> states = (from s in XDocument.Load(@"Foo.xml").Descendants("State")
    select new State
    {
        Name = s.Attribute("Name").Value,
        Capital = s.Attribute("Capital").Value
    }).ToList();

foreach (State state in states)
{
    //do something...
}

//Or get a specific state
var alabama = states.FirstOrDefault(a => a.Name == "Alabama");

Upvotes: 1

Related Questions