码迷,mamicode.com
首页 > 其他好文 > 详细

xml特性重载

时间:2015-04-02 18:07:23      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

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.

xml特性重载

标签:

原文地址:http://www.cnblogs.com/chenru1988/p/4387369.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!