Search code examples
c#linq-to-xmlxelementdynamic-controls

how can I dynamically add XElements to an XML file?


okay, so my program will be saving any number of XElements that are given by the user from a NumericUpDown control during runtime. The way I wrote this with XMLtextWriter is as follows:

public void XMLWriteNewL4Module()
    {
        int i;
        String workingDir = Directory.GetCurrentDirectory();
        //create a new file in the working directory
        XmlTextWriter textWriter = new XmlTextWriter("Level4Modules.xml", null);
        //opens the document
        textWriter.WriteStartDocument();                                      //Document Start
        //first student
        textWriter.WriteStartElement("Module");                                //Module start
        //Module title element
        textWriter.WriteStartElement("Title", "");                                //Title start
        textWriter.WriteString(this.textBoxModuleTitle.Text);
        textWriter.WriteEndElement();                                             //Title end
        //Module code element
        textWriter.WriteStartElement("Code", "");                                 //Code start
        textWriter.WriteString(this.textBoxModuleCode.Text);
        textWriter.WriteEndElement();                                             //Code end
        //Credit value element
        textWriter.WriteStartElement("Credit Value", "");                         //Credit value start
        textWriter.WriteString(this.textBoxModuleCreditValue.Text);
        textWriter.WriteEndElement();                                             //Credit value end 
        //Assessments element
        textWriter.WriteStartElement("Assessments", "");                          //Assessments start
        for (i = 0; i < numericUpDownNoOfAssessments.Value; i++)
        {
            textWriter.WriteStartElement("Assessment", "");                             //Assessment start
            textWriter.WriteStartElement("Assessment Type", "");                        //Assessment type start
            textWriter.WriteString((comboBoxAssessments[i] as ComboBox).Text);
            textWriter.WriteEndElement();                                               //Assessment type end 
            textWriter.WriteStartElement("Assessment Grade", "");                       //Assessment grade start
            textWriter.WriteString((textBoxAssessments[i] as TextBox).Text);
            textWriter.WriteEndElement();                                               //Assessment grade end 
            textWriter.WriteStartElement("Assessment Weighting", "");                   //Assessment weighting start
            textWriter.WriteString((assessmentWeightingTextBox[i] as TextBox).Text);
            textWriter.WriteEndElement();                                               //Assessment weighting end 
            textWriter.WriteEndElement();                                               //Assessment end 
        }
        textWriter.WriteEndElement();                                             //Assessments end 
        textWriter.WriteEndElement();                                          //Module end
        //end the document
        textWriter.WriteEndDocument();                                        //Document end
        //close the writer
        textWriter.Close();
        Console.ReadLine();
    }

but that way doesn't allow me to append the XML file so I tried writing it like this:

public void XMLWriteNewL4Module()
    {
        String workingDir = Directory.GetCurrentDirectory();
        int i;
        if (File.Exists(workingDir + @"Level4Modules.xml") == false)
        {
            //create a new file in the working directory
            XmlTextWriter textWriter = new XmlTextWriter("Level4Modules.xml", null);
            textWriter.WriteStartElement("Modules");
            textWriter.WriteEndElement();
            textWriter.Close();
        }


        XElement xDoc = XElement.Load(workingDir + @"Level4Modules.xml");
        xDoc.Add(
        new XElement("Module",
            new XElement("Title", this.textBoxStudentFirstName.Text),
            new XElement("Code", this.textBoxStudentSurname.Text),
            new XElement("Credit Value", this.textBoxStudentIDNewUser.Text),
            new XElement("Assessments", 
            for (i = 0; i < numericUpDownNoOfAssessments.Value; i++)
            {
                new XElement("Assessment Type", (comboBoxAssessments[i] as ComboBox).Text),
                new XElement("Assessment Grade",),
                new XElement("Assessment Weighting",))
            }
        ));
        xDoc.Save(workingDir + @"\Students.xml");

    }

and this doesn't let me use a for loop inside of the new XElement declaration (which is understandable) so I need a way around it because I'm absolutely stumped. The error message that it shows says "invalid expression term 'for' " because obviously c# doesn't like you starting a for loop inside an XElement. Any ideas how I can get around this?


Solution

  • You can place the for loop into a new method, that returns an XElement[], and call the method where you need the child items. Something like this:

    C#

    new XElement("Module",
                new XElement("Title", this.textBoxStudentFirstName.Text),
                new XElement("Code", this.textBoxStudentSurname.Text),
                new XElement("Credit Value", this.textBoxStudentIDNewUser.Text),
                new XElement("Assessments", GetAssessments())); //the returned items will be added as child items to the "Assessments" node
    

    C#

    XElement[] GetAssessments()
    {
        var result = new List<XElement>();
        for (int i = 0; i < numericUpDownNoOfAssessments.Value; i++)
        {
            result.Add(new XElement("Assessment Type", (comboBoxAssessments[i] as ComboBox).Text));
            result.Add(new XElement("Assessment Grade", ""));
            result.Add(new XElement("Assessment Weighting", ""));
        }
        return result.ToArray();
    }
    

    If there is some contextual info, you can pass it into the new method as a parameter. I hope I could help.