Friday, 10 June 2016

XML : Deserialize XML collection with possible different elements but same class

I am trying to write something like Nunit report analyzer/collector for failed tests and I am stuck while trying deserialize test report.

Nunit report have following structure:

  <test-results ... >      <test-suite>          <results>              <test-suite> or <test-case> bunch of elements                  <failure> // optional          </results>      </test-suite>  </test-results>    

So test-suite element could have either results collection with other test-suite elements or results collection with test-case elements. Since test-suite have same attributes as test-case it can be serialized as one type class:

  [Serializable()]  public class TestResult  {      [XmlAttribute("name")]      public String Name { get; set; }      [XmlAttribute("executed")]      public String Executed { get; set; }        [XmlAttribute("success")]      public String Success { get; set; }        [XmlElement("failure", IsNullable = true)]      public Failure Failure { get; set; }        [XmlElement("results")]      public Results Results { get; set; }        [XmlAttribute("result")]      public String Result { get; set; }        [XmlAttribute("time")]      public String Time { get; set; }        [XmlAttribute("asserts")]      public String Asserts { get; set; }      }    [Serializable()]  public class TestCase : TestResult  {    }    [Serializable()]  public class TestSuite : TestResult  {      [XmlAttribute("type")]      public String Type { get; set; }  }    

And Results class suppose to have a list of test-suites or test-cases:

  [Serializable()]      public class Results      {          [XmlArray("results")]          [XmlArrayItem("test-case", Type = typeof(TestCase))]          [XmlArrayItem("test-suite", Type = typeof(TestSuite))]          public List<Result> Result { get; set; }      }    

Here TestCase and TestSuite are empty subclasses of Result since arrtibutes and elements are same. There is no items serialized this way from collection. If I'am trying to specify multiple ArrauItem-s without dedicated type for each item pardser considers it unbiguous.

How can I actually serialzie collection with different but related elements?

No comments:

Post a Comment