I have a XML file like this:
<Document>
<Tests Count="4">
<Test>
<Name>test with a</Name>
<Type>VI test</Type>
<Result>Pass</Result>
</Test>
<Test>
<Name>test plot</Name>
<Type>Curve test</Type>
<Result>Fail</Result>
</Test>
<Test>
<Name>test fixture</Name>
<Type>Leakage test</Type>
<Result>Pass</Result>
</Test>
<Test>
<Name>test fixture</Name>
<Type>Leakage test</Type>
</Test>
</Tests>
</Document>
I made a class to contain each “Test” in it:
class TestGroup
{
public string TestName { get; set; }
public string TestType { get; set; }
public string TestResult { get; set; }
}
Since I am very noob at XML, at the moment I get data like this (ztr is XmlDocument):
public List<TestGroup> GetTestGroups()
{
List<TestGroup> TestNode = new List<TestGroup>();
string[] type_t = new string[GetTestsNumber()];
string[] name_t = new string[GetTestsNumber()];
string[] result_t = new string[GetTestsNumber()];
//name
string xpath = "/Document/Tests/Test";
int i = 0;
foreach (XmlElement Name in ztr.SelectNodes(xpath))
{
name_t[i] = Name.SelectSingleNode("Name").InnerText;
i++;
}
///////////
//result
xpath = "/Document/Tests/Test";
i = 0;
foreach (XmlElement Result in ztr.SelectNodes(xpath))
{
result_t[i] = Result.SelectSingleNode("Result").InnerText;
i++;
}
/////////////////
xpath = "/Document/Tests/Test";
i = 0;
foreach (XmlElement Type in ztr.SelectNodes(xpath))
{
type_t[i] = Type .SelectSingleNode("Type").InnerText;
i++;
}
int count = type_t.GetLength(0);
for (i = 0; i < count; i++)
{
LUTestGroup node = new LUTestGroup();
node.TestName = name_t[i];
node.TestType = type_t[i];
node.TestResult = result_t[i];
TestNode.Add(node);
}
return TestNode;
}
Obviously this way is pretty dangerous. It itterates separate times in the xml time and each time adds one property to the class. Also if you note in the example xml file. the last Test does noet have a Result node so the code I wrote sometimes crashes when I feed in different XML files.
Can you help me please write a method to safely get the List to be filled by all Tests avilable in XML file and if any of them does not have a node, the method would not crash? and must important, does the job in ONE GO!
Thanks
(As noted in comments.)
The LINQ to XML version is really easy:
Note that the cast from
XElementtostringwill return null if you give it a nullXElementreference, so in your “leakage test” case, you’d end up with anLUTestGroupwith a nullTestResultproperty.