我有以下 Employee 类。我需要从此类生成一个 xml,这样只允许使用 One 属性。要么是薪水1,要么是薪水2。
如果从数据库获取的salary1大于Salary2,生成的XML应该只包含salary1 XMLElement,而salary2 XML Elment应该在生成的XML中不存在
现在我在生成的 XML 中获得了这两个元素。
如果从数据库获取的salary2大于Salary1,则生成的XML应仅包含salary2 XMLElement,而生成的XML中不应包含salary1 XML Elment。
我尝试过使用选择标识符,但我无法理解它。
公开课节目 {
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;
}
}
}
并按原样序列化对象。
希望对您有帮助。
谢谢大家的回答和指导。但在我的场景中,由于某些原因,我无法拥有像工资这样的单一属性。将数据类型从 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();
}
}