Reputation: 79
XmlSerializer ignores class attributes. I'm writing simple serializer, and I used [Serializable]
and [NonSerialized]
attributes, also I tried to use [XmlRoot]
and [XmlIgnore]
. And I've noticed, although the field has the attribute [NonSerialized]
it is serialized.
And it also ignores other attributes such as [XmAtribute]
. Then I've noticed that it's even not necessary to use any attributes, and I can serialize class without these attributes, how can I ignore some fields?
My class:
[Serializable]
public class Route
{
int busNumber;
string busType, destination;
DateTime departure, arrival;
[NonSerialized]DateTime creationDate;
...
}
And I'm trying to serialize List<Route>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream stream = File.OpenWrite(Environment.CurrentDirectory + "\\routes.xml");
XmlSerializer xmlSer = new XmlSerializer(typeof(List<Route>));
xmlSer.Serialize(stream, ((FileForm)ActiveMdiChild).routes);
stream.Close();
}
Upvotes: 1
Views: 1725
Reputation: 18105
I believe that you are looking for the XmlIgnoreAttribute. Also, properties that need to be serialized must be declared as public
.
Usage as follows:
public class Route
{
public int busNumber;
public string busType, destination;
public DateTime departure, arrival;
[XmlIgnore]
public DateTime creationDate;
// how to ignore a property
private int ignored;
[XmlIgnore]
public int Ignored { get { return ignored; } set { ignored = value; } }
}
Upvotes: 2
Reputation: 3531
You are using a wrong attribute. Since you are using a XmlSerializer, you should use the XML specific attributes. Check this link
Upvotes: 0
Reputation: 2655
Try overriding the Serializer:
// Return an XmlSerializer used for overriding.
public XmlSerializer CreateOverrider()
{
// Create the XmlAttributeOverrides and XmlAttributes objects.
XmlAttributeOverrides xOver = new XmlAttributeOverrides();
XmlAttributes attrs = new XmlAttributes();
/* Setting XmlIgnore to false overrides the XmlIgnoreAttribute
applied to the Comment field. Thus it will be serialized.*/
attrs.XmlIgnore = false;
xOver.Add(typeof(Group), "Comment", attrs);
/* Use the XmlIgnore to instruct the XmlSerializer to ignore
the GroupName instead. */
attrs = new XmlAttributes();
attrs.XmlIgnore = true;
xOver.Add(typeof(Group), "GroupName", attrs);
XmlSerializer xSer = new XmlSerializer(typeof(Group), xOver);
return xSer;
}
public void SerializeObject(string filename)
{
// Create an XmlSerializer instance.
XmlSerializer xSer = CreateOverrider();
// Create the object to serialize and set its properties.
Group myGroup = new Group();
myGroup.GroupName = ".NET";
myGroup.Comment = "My Comment...";
// Writing the file requires a TextWriter.
TextWriter writer = new StreamWriter(filename);
// Serialize the object and close the TextWriter.
xSer.Serialize(writer, myGroup);
writer.Close();
}
https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlattributes.xmlignore.aspx
Upvotes: 0