XmlSerializer忽略类属性。我正在编写简单的序列化程序,我使用了[Serializable]和[NonSerialized]属性,还尝试使用[XmlRoot]和[XmlIgnore]。我注意到,尽管字段具有属性[NonSerialized],但它是序列化的。
它还忽略了其他属性,如[XmAtribute]。然后我注意到,甚至没有必要使用任何属性,而且我可以在没有这些属性的情况下序列化类,如何忽略一些字段呢?
我的班级:
[Serializable]
public class Route
{
int busNumber;
string busType, destination;
DateTime departure, arrival;
[NonSerialized]DateTime creationDate;
...
}我正在尝试序列化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();
}发布于 2016-12-22 16:36:41
我相信你是在找XmlIgnoreAttribute。另外,需要序列化的属性必须声明为public。
用法如下:
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; } }
}发布于 2016-12-22 16:35:08
尝试重写序列化程序:
// 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
发布于 2016-12-22 16:36:12
您使用了错误的属性。由于您使用的是XmlSerializer,所以应该使用特定于XML的属性。检查这个链接
https://stackoverflow.com/questions/41287717
复制相似问题