Search code examples
c#xmlxsdxsd-validation

Generate Choice Node in C# XML


I have below Employee class. I need to generate a xml from this class, such that either One property is only allowed. It is either salary1 or salary2.

If salary1 got from Database is greater than Salary2, the generated XML should contain only salary1 XMLElement and salary2 XML Elment should be absent in generated XML

Right now i get both elements in generated XML.

If salary2 got from Database is greater than Salary1, the generated XML should contain only salary2 XMLElement and salary1 XML Elment should be absent in generated XML.

I have tried using choice identifier, I was not able to understand it.

public class Program {

    public class Employee 
    {

        public int Salary1 { get; set; }
        public int Salary2 { get; set; }

    }

       public static class Database
        {
            public static int Salary1 = 100;
            public static int Salary2= 50;
        }

    public static void Main(string[] args)
    {

        XmlSerializer xsSubmit = new XmlSerializer(typeof(Employee));

        Employee subReq;
        if (Database.Salary1 > Database.Salary2)
        {
            subReq = new Employee { Salary1 = Database.Salary1 };
        }
        else
        {
            subReq = new Employee { Salary2 = Database.Salary2 };
        }
        var xml = "";

        using (var sww = new StringWriter())
        {
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                xsSubmit.Serialize(writer, subReq);
                xml = sww.ToString(); // Your XML
            }
        }

        Console.WriteLine(xml);
        Console.ReadLine();

    }
}

}


Solution

  • Thanks guys for your answers and guidance. But my scenario i cannot have one single property like salary for some reasons.Changing Data Type from Int to String solves the issue

    public static class Program
    {
    
      public class Employee
      {
         public string Salary1 { get; set; }
         public string Salary2 { get; set; }
      }
    
      public static class Database
      {
         public static int? Salary1 = 100;
         public static int? Salary2 = 50;
      }
    
      public static void Main(string[] args)
      {
         XmlSerializer xsSubmit = new XmlSerializer(typeof(Employee));
         Employee subReq;
         if (Database.Salary1 > Database.Salary2)
         {
            subReq = new Employee{ Salary1=Database.Salary1.ToString()};
         }
         else
         {
            subReq = new Employee{ Salary2=Database.Salary2.ToString()};
         }
         var xml = "";
    
         using (var sww = new StringWriter())
         {
            using (XmlWriter writer = XmlWriter.Create(sww))
            {
                xsSubmit.Serialize(writer, subReq);
                xml = sww.ToString(); // Your XML
            }
         }
         Console.WriteLine(xml);
         Console.ReadLine();
      }
    }