In this article we will read trx file by using Linq to XML
Introduction
Sometime back, I found an article in dotnet funda about Read trx file from C#.
That was a nice article being presented where the author described a way of reading "trx" file.
In this post we will look into an alternative way of doing so using Linq to XML
Straight to Experiment
A typical "trx" file looks as under

And out of which we will be interested in processing the records under the "Results" node

As can be figure out that we can get information about both the success and failed test cases.
So let us write the program
string source = @"D:\Source.trx";
var lstTrxEntity = new List();
XDocument xDoc = XDocument.Load(source);
XNamespace defaultNs = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
var UnitTestResultNode = (from data in xDoc.Descendants(defaultNs + "Results")
select data).Descendants(defaultNs + "UnitTestResult").ToList();
var recordSet = (from src in UnitTestResultNode
select new
{
TestRunID = src.Attribute("testId").Value
,
TestName = src.Attribute("testName").Value
,
TestOutcome = src.Attribute("outcome").Value
,
Message = src
.Descendants(defaultNs + "Output")
.Descendants(defaultNs + "ErrorInfo")
.Descendants(defaultNs + "Message")
,
StackTrace = src
.Descendants(defaultNs + "Output")
.Descendants(defaultNs + "ErrorInfo")
.Descendants(defaultNs + "StackTrace")
});
foreach (var record in recordSet)
{
lstTrxEntity.Add(new TrxEntity
{
TestRunID = record.TestRunID,
TestName = record.TestName,
TestOutcome = record.TestOutcome,
Message = record.Message.Select(i => i.Value).FirstOrDefault(),
StackTrace = record.StackTrace.Select(i => i.Value).FirstOrDefault()
});
}
grView.DataSource = lstTrxEntity.OrderBy(o => o.TestOutcome).ToList();
}
Now let us understand as what is going on.First we are getting the records upto UnitTestResultNode.And then filtering teh same based on te information we are interested in.Finally we are displaying those to the grid.

Conclusion
So this article, has given some insite about another way of parsing "trx" file.Thanks for reading.