Search code examples
c#xmlxelement

How to recover all the XML elements in an XML tag?


This is a sample of my XML:

        <Library>
            <Stack>
                <Book>
                    <Author>....</Author>
                    <Date>....</Date>
                </Book>
                <Book>
                    <Author>....</Author>
                    <Date>....</Date>
                </Book>
            </Stack>
            <Stack>
                <SectionScience>
                    <Book>
                        <Author>....</Author>
                        <Date>....</Date>
                    </Book>
                </SectionScience>
                <SectionHorror>
                    <Book>
                        <Author>....</Author>
                        <Date>....</Date>
                    </Book>
                </SectionHorror>
                <Book>
                    <Author>....</Author>
                    <Date>....</Date>
                </Book>
            </Stack>
        </Library>

I've attempted to implement a method that recovers all this information, but it doesn't work: It recovers only one item in a Stack, and I want it to recover all the elements in the Stack.

What I get is this:

Stack 1 : first book ;

Stack 2 : first Section

This is my code:

 private void ConstructionInterface()
 {
   XElement docX = XElement.Load(Application.StartupPath + @"\Library.xml");
   foreach (XElement elemColone in docX.Descendants("Stack"))
     {
       if (elemColone.Element("SectionHorror") != null)
         CreateSectionHorror( elemColone.Element("SectionHorror"));
       else if (elemColone.Element("SectionScience") != null)
         CreateSectionScience( elemColone.Element("SectionScience"));
       else if (elemColone.Elements("Book") != null)
         CreateBook( elemColone.Element("Book"));
        }
    }

Solution

  • You need to iterate through each Stack's children as well:

    foreach (XElement elemColone in docX.Descendants("Stack"))
    {
        foreach (var sectionOrBook in elemColone.Elements())
        {
            if (sectionOrBook.Name == "SectionHorror")
                CreateSectionHorror(sectionOrBook);
            else if (sectionOrBook.Name == "SectionScience")
                CreateSectionScience(sectionOrBook);
            else if (sectionOrBook.Name == "Book")
                CreateBook(sectionOrBook);
        }
    }