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

时间:2013-04-10 05:24:16

标签: c# .net xml serialization xml-serialization

代码:

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

    [XmlElement("Amount")]
    public decimal Amount { get; set; }

    public int companyid { get; set; }
}

现在我只想序列化那些用[XmlElement]指定的,不能序列化的公司ID。

那么,我该怎么办?

1 个答案:

答案 0 :(得分:1)

这是我在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; }
}