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".
<OpeningTag><AnotherOpeningTag>Information</AnotherClosingTag></ClosingTag>
"Etiam venenatis feugiat erat, in egestas tellus lacinia eu. Phasellus volutpat lectus nec tristique volutpat. Sed tempus sollicitudin mauris eu blandit.<OpeningTag><AnotherOpeningTag>Information</AnotherClosingTag></ClosingTag> 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("<") && text.EndsWith(">"))
{
txtXml += text + "\n";
}
else
{
string regexPattern = @"(<.*>)(.*)(<\/.*>)";
Regex regex = new Regex(regexPattern, RegexOptions.Singleline);
MatchCollection collection = regex.Matches(text);
var list = collection.Cast<Match>().Select(match => match.Value).ToList();
for (int i = 0; i < 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.