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();
}
答案 0 :(得分:2)
我相信你正在寻找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; } }
}
答案 1 :(得分:0)
尝试重写序列化程序:
// 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();
}
答案 2 :(得分:0)
您使用的是错误的属性。由于您使用的是XmlSerializer,因此应使用XML特定的属性。检查此链接