Duplicate:
Omitting all xml namespaces when serializing an object? Not the same.. I want in the other way: Deserialize!
I
I had run into a similar challenge with a proxy class. For reasons that I won't go into, I needed to serialize the class manually using the XmlSerializer on web server and deserialize on client. I was not able to find an elegant solution online, so I just avoided the issue by removing the XmlTypeAttribute from the proxy class manually after I auto-generated it in Visual Studio.
I kept coming back to see if there was a way to get the namespace to workout. Here is how I got it working without the need to modify the auto-generated classes. I ended up using an XmlTextReader to return the desired namespace on nodes matching a property name. There is room for improvement, but i hope it helps someone.
class Program
{
static void Main(string[] args)
{
//create list to serialize
Person personA = new Person() { Name = "Bob", Age = 10, StartDate = DateTime.Parse("1/1/1960"), Money = 123456m };
List listA = new List();
for (int i = 0; i < 10; i++)
{
listA.Add(personA);
}
//serialize list to file
XmlSerializer serializer = new XmlSerializer(typeof(List));
XmlTextWriter writer = new XmlTextWriter("Test.xml", Encoding.UTF8);
serializer.Serialize(writer, listA);
writer.Close();
//deserialize list from file
serializer = new XmlSerializer(typeof(List));
List listB;
using (FileStream file = new FileStream("Test.xml", FileMode.Open))
{
//configure proxy reader
XmlSoapProxyReader reader = new XmlSoapProxyReader(file);
reader.ProxyNamespace = "http://myappns.com/"; //the namespace of the XmlTypeAttribute
reader.ProxyType = typeof(ProxysNamespace.Person); //the type with the XmlTypeAttribute
//deserialize
listB = (List)serializer.Deserialize(reader);
}
//display list
foreach (ProxysNamespace.Person p in listB)
{
Console.WriteLine(p.ToString());
}
Console.ReadLine();
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime StartDate { get; set; }
public decimal Money { get; set; }
}
namespace ProxysNamespace
{
[XmlTypeAttribute(Namespace = "http://myappns.com/")]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
public decimal Money { get; set; }
public override string ToString()
{
return string.Format("{0}:{1},{2:d}:{3:c2}", Name, Age, Birthday, Money);
}
}
}
public class XmlSoapProxyReader : XmlTextReader
{
List