在 C# 中生成选择节点 XML

Generate Choice Node in C# XML

我有以下员工class。我需要从这个 class 生成一个 xml,这样就只允许一个 属性。它是 salary1 或 salary2.

如果从数据库中获取的salary1大于Salary2,生成的XML应该只包含salary1XML元素和salary2XML生成的XML元素应该不存在

现在我在生成的 XML.

中得到了两个元素

如果从数据库中获取的salary2大于Salary1,生成的XML应该只包含salary2XML元素和salary1XML生成的XML元素应该不存在.

我试过使用选择标识符,但我无法理解它。

public class 程序 {

    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();

    }
}

}

试试这个:

public class Employee
{
    private int salary;

    [XmlIgnore]
    public int Salary1 { get; set; }

    [XmlIgnore]
    public int Salary2 { get; set; }

    [XmlAttribute(AttributeName = "Salary")]
    public int SalaryToSerialize
    {
        get
        {
            salary = Math.Max(this.Salary1, this.Salary2);
            return salary;
        }
        set
        {
            salary = value;
        }    
    }
}

并按原样序列化对象。

希望对您有所帮助。

感谢大家的回答和指导。但是我的情况是我不能有一个单一的 属性 像某些人的薪水 reasons.Changing 从 Int 到 String 的数据类型解决了这个问题

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();

    }

}