Serialization&Deserialization
I did program for xml serialization but i get error on this pgm.... plz clear my bug...
public class Orders
{
public Book[] Books;
}
public class Book
{
//[XmlElement("Newbooooook", typeof(ExpandedBook))]
public string ISBN;
public string BookName;
}
public class ExpandedBook : Book
{
public bool NewEdition;
}
private void Serialize_Click(object sender, EventArgs e)
{
XmlSerializer seer =new XmlSerializer(typeof(Orders));
TextWriter writer = new StreamWriter(@"d:\xmlarra.xml");
Orders myOrders = new Orders();
ExpandedBook b = new ExpandedBook();
b.BookID= txtid.Text;
b.BookName = txtname.Text;
b.NewEdition = bool.Parse(txtbool.Text);
myOrders.Books = new ExpandedBook[] { b };
// Serializes the object.
seer.Serialize(writer, b);
writer.Close();
}
private void txtbool_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cb = (ComboBox)sender;
if (!cb.Focused)
{
return;
}
}
Ruchi HPosted Jul 25, 2013, 2:13 AM
First your code is giving error "Unable to cast object of type 'WindowsFormsApplication1.ExpandedBook' to type 'WindowsFormsApplication1.Orders"
Because you have given type of Orders when initializing XMLSerializer and passing ExpandedBook type in Serialize method.
Then it is giving error "The type WindowsFormsApplication1.ExpandedBook was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically."
Because you have declared array of Book in Orders class so ExpandedBook class will be unknown to Orders class as it is child of Book class.
So declare array of ExpanededBook class in Orders class.
Here is the working code. Just replace strings to your textboxes :
public class Orders
{
public ExpandedBook[] Books;
}
public class Book
{
//[XmlElement("Newbooooook", typeof(ExpandedBook))]
public string BookID;
public string BookName;
}
public class ExpandedBook : Book
{
public bool NewEdition;
}
private void button1_Click(object sender, EventArgs e)
{
XmlSerializer seer = new XmlSerializer(typeof(Orders));
TextWriter writer = new StreamWriter(@"d:\xmlarra.xml");
Orders myOrders = new Orders();
ExpandedBook b = new ExpandedBook();
b.BookID = "aaa";
b.BookName = "AAA";
b.NewEdition = true; ;
myOrders.Books = new ExpandedBook[1] { b };
// Serializes the object.
seer.Serialize(writer, myOrders);
writer.Close();
}
VijayPosted Jul 25, 2013, 2:48 AM
Now i want to do deserializing for which i serialized xml file..... that is xml to object
Iftikar HussainPosted Jul 25, 2013, 2:18 AM
Try like this
public class Orders
{
public ExpandedBook[] Books;
}
public class Book
{
//[XmlElement("Newbooooook", typeof(ExpandedBook))]
public string BookID;
public string BookName;
}
public class ExpandedBook : Book
{
public bool NewEdition;
}
private void Serialize_Click(object sender, EventArgs e)
{
XmlSerializer seer = new XmlSerializer(typeof(Orders));
Regards,
Iftikar