For example, I have the usual form with two textbox and one button . As planned, after entering any text and pressing a button, these values ​​should be added to the XML file. With the formation of the body xml using xml, I figured out without problems. MSDN on this account has an exhaustive reference:

 XElement xmlTree1 = new XElement("Root", new XElement("Child1", 1), new XElement("Child2", 2), new XElement("Child3", 3), new XElement("Child4", 4), new XElement("Child5", 5), new XElement("Child6", 6) ); 

But I cannot understand the AddAfterSelf method from the same directory. How to make it so that after entering any values, they are added to the end of the document? Let it not even textbox, and the value taken from Console.Readline() ;

Addition:

The community got me thinking, but on the whole is fair. Since at the time of the answer myself, I did not fully understand how it works :)
When I asked a question, I did not stop looking for an answer and found it.

The original goal was to add a new child to the root of Root. I thought that this was done through the AddAfterSelf method, but somewhere in the subconscious I understood that this was probably not correct (which is obvious, because it does not work the way I want). Then I tried to add an element by simply adding a new XElement("Child1", Textbox.text), but that didn't help either. The file is still the same. But after persistent re-reading of MSDN and examples of other programmers, I realized my mistake.
That is, I did not fulfill a few obvious points that exist behind the scenes and are clear as 2x2 to those who have more experience.
In fact, first I had to load the file I am going to work with: var EventLibrary = XElement.Load("EventFile.xml");
After that, I needed to call the XContainer. Add method XContainer. Add XContainer. Add with the name of the root, so that later XContainer knew that there is a Root, and that there is a child element. Well, then save the result of the work to a file.
After that, my XML document began to fill as I wanted.

  • 3
    Of course, I apologize, but according to the answer given to you and your decision to open and save the file, I still did not understand what the problem was and here AddAfterSelf - Alexander Muksimov
  • Added an explanation of your answer. - Amateur

2 answers 2

For example:

 int n = xmlTree1.Elements().Count() + 1; string text = "Console input or textbox text or whatever"; xmlTree1.Add(new XElement("Child" + n, text)); 

    I got out of the situation in the following way:

    • I open the document with XElement.load (file);
    • Then, I do ADD (I describe the body of the document)
    • Save the document with XElement.save (file);