Generating an XML based on the elements of a Generic list

11 Views Asked by At

I am trying to build an XML document based on Elements obtained from a list. Indeed my list returns an object with two fields (Titre and Contenu). Right now via my code, I get this

But I would like for each Category, have a title and all items related to this category. For the moment at each entrance of my list, it generates a category. While I am having the category that contains an item and a title. Like this

I put my code in the appendix. I know I'm new in the area and that there's necessarily a lack in my design. Any help Will Be Appreciated.

1

There are 1 best solutions below

0
On

public void GenerateXML(XMLRecord file) { XmlDocument doc = new XmlDocument();

            XmlNode rootNode = doc.CreateElement ("Side");

            doc.AppendChild(rootNode);

            foreach (var rec in file.Records)
             {
                XmlElement category = null;
                category = doc.CreateElement("Category");


            XmlElement titre = null;

            XmlElement item = null;

            if (rec.Type == "Titre")
            {
                titre = doc.CreateElement("Titre");
                titre.InnerText = rec.Contenu;
                category.AppendChild(titre);
                rootNode.AppendChild(category);
            }
            else if (rec.Type=="Item")
            {
                item = doc.CreateElement("Item");
                item.InnerText = rec.Contenu;
                category.AppendChild(item);
                rootNode.AppendChild(category);
            }               

        }
            doc.AppendChild(rootNode);                              
            doc.Save(@"c:\test-doc.xml");

        }