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. So I don't want to set the XmlIgnore attribute directly in the Tag class. And I don't want to use the nullable wrapper for 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.
Thanks in advance!
The error here is in the argument member string
in xOver.Add(typeof(Tag), "GUID", attrs)
.
You are passing the XMLElement Name
not the Member Name
which is "Guid" not "GUID".
The line should be xOver.Add(typeof(Tag), "Guid", attrs)
.
I've tested it and it works. Hope it does for you!