仅序列化指定[XmlElement]的属性,而不更改原始类

本文关键字:原始 属性 序列化 XmlElement | 更新日期: 2023-09-27 18:08:27

代码:

[Serializable]
public class MyClass
{
    [XmlElement("Company")]
    public string Company { get; set; }
    [XmlElement("Amount")]
    public decimal Amount { get; set; }
    public int companyid { get; set; }
}

现在我只想序列化用[XmlElement]指定的那些,companyid不需要序列化。

那么,我能做什么呢?

仅序列化指定[XmlElement]的属性,而不更改原始类

下面是我在LinqPad中创建的一个简单示例。Main方法的前4行设置了一个XmlAttributeOverrides实例,然后该实例用于告诉XmlSerializer不要序列化companyid属性。

void Main()
{
    //Serialize, but ignore companyid
    var overrides = new XmlAttributeOverrides();
    var attributes = new XmlAttributes();
    attributes.XmlIgnore = true;
    overrides.Add(typeof(MyClass), "companyid", attributes);
    using(var sw = new StringWriter()) {
        var xs = new XmlSerializer(typeof(MyClass), overrides);
        var a = new MyClass() { 
                                       Company = "Company Name", 
                                       Amount = 10M, 
                                       companyid = 7 
                                   };
        xs.Serialize(sw, a);
        Console.WriteLine(sw.ToString());
    }
}
[Serializable]
public class MyClass
{
    [XmlElement("Company")]
    public string Company { get; set; }
    [XmlElement("Amount")]
    public decimal Amount { get; set; }
    public int companyid { get; set; }
}

该程序的输出为:

<?xml version="1.0" encoding="utf-16"?>
<MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Company>Company Name</Company>
  <Amount>10</Amount>
</MyClass>

如果您需要此代码来检查类,以根据不存在的XmlElementAttribute来确定要排除哪些属性,那么您可以修改以上代码以使用反射来枚举对象的属性。对于每个没有XmlElementAttribute的属性,将一个项添加到overrides实例中。

例如:

void Main()
{
    //Serialize, but ignore properties that do not have XmlElementAttribute
    var overrides = new XmlAttributeOverrides();
    var attributes = new XmlAttributes();
    attributes.XmlIgnore = true;
    foreach(var prop in typeof(MyClass).GetProperties())
    {
        var attrs = prop.GetCustomAttributes(typeof(XmlElementAttribute));
        if(attrs.Count() == 0)
            overrides.Add(prop.DeclaringType, prop.Name, attributes);
    }
    using(var sw = new StringWriter()) {
        var xs = new XmlSerializer(typeof(MyClass), overrides);
        var a = new MyClass() { 
                                Company = "Company Name", 
                                Amount = 10M, 
                                companyid = 7,
                                blah = "123" };
        xs.Serialize(sw, a);
        Console.WriteLine(sw.ToString());
    }
}
[Serializable]
public class MyClass
{
    [XmlElement("Company")]
    public string Company { get; set; }
    [XmlElement("Amount")]
    public decimal Amount { get; set; }
    public int companyid { get; set; }
    public string blah { get; set; }
}