Actually, I would like to save all components and variables which are contained in MainForm.
The IDE does this for you.
The mainform.lfm saves a text representation of the main TForm class descendant, and a text representation of all the controls it contains.
The variables are all named in the main form's .pas (or .pp) file. You could parse this to look for, say, just the global variables (if that is what you are after).
However, getting the variables' values would be trickier. Being variable, the values ... vary. So if you are after variable value data you'll have to be more specific about at what point in the app's lifecycle you wanted the variables' values, and if you wanted only the values of simple variables, or also values of records, arrays, and non-GUI classes etc.
Saving this data is fairly straightforward, as the code you showed indicates. But the IDE does a perfect job of completing this task, so I don't see the point of reinventing that wheel.
On the other hand the code you show for reconstructing a form and its components is nonsense. On the pretext of avoiding name clashes the code tries to strip out all the form's contents.
What good is a reconstructed empty form? You might just as well call Application.CreateForm(xx, yy); and be done with it.
Presumably the point of the code you found was to save and later rebuild an entire form. This is a non-trivial exercise, and the IDE Designer devotes hundreds if not thousands of lines to this task, since this is exactly what the IDE has to do when it opens a GUI project. Don't imagine that it is a ten-liner to rebuild a form from its .pas and .lfm files and recursively construct each control and any sub controls and get them all parented properly after finding all the required registered classes.