我在Employee类之下。我需要从这个类生成一个xml,这样只允许一个属性。它是salary1或salary2。
如果来自Database的salary1大于Salary2,则生成的XML应该只包含salary1 XMLElement和salary2 XML Elment应该在生成的XML中不存在
现在我在生成的XML中获得了两个元素。
如果来自Database的salary2大于Salary1,则生成的XML应仅包含salary2 XMLElement和salary1 XML Elment应该在生成的XML中不存在。
我尝试过使用选择标识符,但我无法理解它。
公共课程 {
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();
}
}
}
答案 0 :(得分:0)
试试这个:
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;
}
}
}
并按原样序列化对象。
希望它会对你有所帮助。
答案 1 :(得分:0)
谢谢你们的回答和指导。但我的情况是因为某些原因我不能拥有像薪水这样的单一属性。从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();
}
}