XmlIgnore是一个自定义属性,用来指明在序列化时是否序列化一个属性。如下面的例子:
public class Group { public string GroupName; [XmlIgnore] public string Comments; }
在序列化时,其结果如下所示
<?xml version="1.0" encoding="utf-8"?> <Group xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <GroupName>.Net</GroupName> </Group>
我们可以看到,因为设置了XmlIgnore,所以Comments没有被序列化。对于已经设置了XmlIgnore的属性,也可以通过XmlAttributeOverrides 来重新第一序列化时是否需要序列化。
public XmlSerializer CreateOverrider() { XmlAttributeOverrides overr = new XmlAttributeOverrides(); XmlAttributes attrs = new XmlAttributes(); attrs.XmlIgnore = true; overr.Add(typeof(Group), "Comments", attrs); attrs = new XmlAttributes(); attrs.XmlIgnore = false; overr.Add(typeof(Group), "GroupName", attrs); XmlSerializer serilizer = new XmlSerializer(typeof(Group), overr); return serilizer; }
public void SerializeObject(string filename) { XmlSerializer serializer = CreateOverrider(); Group group = new Group(); group.GroupName = ".Net"; group.Comments = "Microsoft .net 3.5"; StreamWriter writer = new StreamWriter(filename); serializer.Serialize(writer, group); writer.Close(); }
这段代码,其结果与上面的相反,序列化了Comments,而不包含GroupName.