xml serialization (interfaces)

S

shrishjain

Hi,

Can someone tell me how can I seralize the following PurchaseOder class
to xml.

public class PurchaseOrder
{
[XmlElement(typeof(USAddress))]
public IUSAddress shipTo;
}
public class USAddress:IUSAddress
{
private string _city;
public string city
{
get {return _city;}
set{_city = value;}
}
}
public interface IUSAddress
{
string city{get; set;}
}


I use the following code to serialize, but it crash on first stament
itself:

XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
PurchaseOrder po = new PurchaseOrder();
po.shipTo = new USAddress();
po.shipTo.city = "my city";
TextWriter writer = new StreamWriter("PurchaseOrder2.xml");
serializer.Serialize(writer, po);
writer.Close();
Any help will me greatly appreciated.

Thanks,
Shrish
 
N

Nicholas Paldino [.NET/C# MVP]

Shrish,

The XmlElement attribute does not do what you think it does in this
context.

Unfortunately, XmlSerialization can not serialize properties that return
interfaces, as it doesn't know what type to use when deserializing it.

If you want to serialize this to XML, you would have to use the SOAP
formatter.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top