Save XML tags and information to another file This was a coding challenge I had done recently. I was given a text file and in it thee was couple of XML tags. The challenge was to get all the XML tags and the information and save it to another file.

The string I am given:

"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec arcu non nisl dapibus scelerisque. Phasellus sagittis ligula vel convallis porttitor. Maecenas sed velit arcu. Proin efficitur ipsum vitae augue semper, bibendum sollicitudin neque egestas".

&lt;OpeningTag&gt;&lt;AnotherOpeningTag&gt;Information&lt;/AnotherClosingTag&gt;&lt;/ClosingTag&gt;

"Etiam venenatis feugiat erat, in egestas tellus lacinia eu. Phasellus volutpat lectus nec tristique volutpat. Sed tempus sollicitudin mauris eu blandit.&lt;OpeningTag&gt;&lt;AnotherOpeningTag&gt;Information&lt;/AnotherClosingTag&gt;&lt;/ClosingTag&gt; Vestibulum consectetur euismod dui, sit amet blandit ex ultrices ac".


This is the code I came up with:

StringReader reader = new StringReader(text);
while ((text = reader.ReadLine()) != null)
{
if (text.StartsWith("&lt;") &amp;&amp; text.EndsWith("&gt;"))
{
    txtXml += text + "\n";

}
else
{
    string regexPattern = @"(&lt;.*&gt;)(.*)(&lt;\/.*&gt;)";
    Regex regex = new Regex(regexPattern, RegexOptions.Singleline);

    MatchCollection collection = regex.Matches(text);

    var list = collection.Cast&lt;Match&gt;().Select(match =&gt; match.Value).ToList();

    for (int i = 0; i &lt; list.Count; i++)
    {
        txtXml += list.ElementAt(i);
    }
}
}


This code works and I am getting all the tags and the information and stuff. I just wanted to know if I could achieve this same task in smaller code or code that executes faster than the current method.
There are some good points raised in comments about the requirements, and you really need to think about them in order to write code that solves the problem.  I can get you started with some feedback though.

Organize your code into a function, so that it's clear what the inputs and outputs are.

StringReader reader = new StringReader(text);
while ((text = reader.ReadLine()


This is a really odd reuse of the variable text.  Declare another string, maybe called line.  But also reconsider if a line-centric approach is even appropriate.  XML is pretty free about where whitespace (including newlines) can appear - what if there is a break between the tag name and some attributes?  How will this affect your solution?

For the Regex @"(&lt;.*&gt;)(.*)(&lt;\/.*&gt;)", note that all of these quantifiers are greedy, which may result in you capturing more than you want.  Of course, it may turn out with some clarified specs that a regex isn't even the appropriate tool to use here.