简体   繁体   English

XmlIgnore 在列表中的属性上

[英]XmlIgnore on a property inside a list

How do I ignore the property which is in a type within a list of another type which I am trying to serialize?如何忽略我要序列化的另一种类型的列表中的类型中的属性?

        public string SerializeTag(List<Tag> reservedTags)
    {
        string timestampFilenamePrefix = DateTime.Now.ToString("yyyyMMddHHmmss");
        string filename = string.Format("ReservedTags_{0}.xml", timestampFilenamePrefix);
        using (var stream = File.Create(filename))
        {
            var objectToBeSerialized = new CompanyDemoData();
            objectToBeSerialized.TagsReserved = reservedTags;

            var namespaces = new XmlSerializerNamespaces();
            namespaces.Add("", "");

            XmlAttributeOverrides xOver = new XmlAttributeOverrides();
            XmlAttributes attrs = new XmlAttributes();
            attrs.XmlIgnore = true;
            xOver.Add(typeof(Tag), "GUID", attrs);

            var serializer = new XmlSerializer(typeof(CompanyDemoData), xOver);
            serializer.Serialize(XmlWriter.Create(stream), objectToBeSerialized, namespaces);

            stream.Flush();
            return filename;
        }
    }
{
    [XmlRoot("CompanyDemoData")]
    public class CompanyDemoData
    {
        [XmlElement("Tag")]
        public List<Tag> TagsReserved { get; set; }
    }
}
namespace Demo.Model
{
    public class Tag
    {
        [XmlElement("TagId")]
        public int ID { get; set; }

        [XmlElement("GUID")]
        public Guid Guid { get; set; }
    }
}

I am trying to avoid the GUID property to be serialized under certain situations.我试图避免在某些情况下对 GUID 属性进行序列化。 So I don't want to set the XmlIgnore attribute directly in the Tag class.所以我不想直接在 Tag class 中设置 XmlIgnore 属性。 And I don't want to use the nullable wrapper for GUID.而且我不想为 GUID 使用可为空的包装器。

I think the error is that I am creating a serializer for the type CompanyDemoData which doesn't contain the property which I am trying to set the override attribute.我认为错误是我正在为 CompanyDemoData 类型创建一个序列化程序,它不包含我试图设置覆盖属性的属性。

Thanks in advance!提前致谢!

The error here is in the argument member string in xOver.Add(typeof(Tag), "GUID", attrs) .这里的错误在xOver.Add(typeof(Tag), "GUID", attrs)的参数member string中。

You are passing the XMLElement Name not the Member Name which is "Guid" not "GUID".您传递的是XMLElement Name而不是“Guid”而不是“GUID”的Member Name

The line should be xOver.Add(typeof(Tag), "Guid", attrs) .该行应该是xOver.Add(typeof(Tag), "Guid", attrs)

I've tested it and it works.我已经对其进行了测试,并且可以正常工作。 Hope it does for you!希望它对你有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM