1

代码:

[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 指定的那些不进行序列化。

那么,我能做些什么呢?

4

1 回答 1

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; }
}
于 2013-04-10T06:18:36.530 回答