I'm trying to find a simple way to deserialize compile-time known element to [Serializable()] class while reading XML where the elemnt itself is not the member of the class (any more). In short, I'm trying to deserialize compile-time known element into local variable instead of member when there is no coresponding member in the class being deserialized.
The trick is that when serializing, the member name is used in XML, eg:
<TheFooString>I'm from Foo.A</TheFooString>
If the class being deserialized doesn't have a member called 'TheFooString' (but I do know what to do with it) I can't find the way to deserialize element into local varibale even though I know the element name and the element type at compile time.
As you can see below, I know how to handle unknwon elements in XML and I even sort of know how to try to deserialize unknwon element into local. I just don't know how xD.
Pleae note that I'm looking for generic solution for any type.
Simple example: Having class
namespace Foo
{
[Serializable()]
public class A
{
public string TheFooString { set; get; }
public string ToXmlString()
{
XmlSerializer serializer = new XmlSerializer(base.GetType());
StringWriter writer = new StringWriter();
serializer.Serialize((TextWriter)writer, this);
return writer.ToString();
}
}
}
and class
namespace Bar
{
[Serializable()]
public class A
{
public string TheBarString { set; get; }
[XmlAnyElement]
public List<XmlElement> UnknownElements { get; set; }
public static A Deserialize( string _sXml )
{
if( _sXml != string.Empty )
{
XmlSerializer serializer = new XmlSerializer(typeof(A));
XmlReader xmlReader = XmlReader.Create(new StringReader(_sXml));
A instance = (A)serializer.Deserialize(xmlReader);
instance.AfterDeserialize();
return instance;
}
return null;
}
static protected T DeserializeXmlElement<T>( XmlElement xmlElement )
{
// Create an XmlSerializer for the specified type (T)
XmlSerializer serializer = new XmlSerializer(typeof(T));
// Create a StringReader to read the XmlElement's XML content
using( StringReader stringReader = new StringReader(xmlElement.OuterXml) )
{
// Deserialize the XML content into an object of type T
return (T)serializer.Deserialize(stringReader);
}
}
public void AfterDeserialize()
{
foreach( XmlElement xmlElement in UnknownElements )
{
if( xmlElement.Name == "TheFooString" )
{
try
{
string BorrowString = DeserializeXmlElement<string>(xmlElement);
}
catch( Exception ex )
{
Console.WriteLine( ex.ToString() );
}
}
}
}
}
}
I will get XML exception while trying
Foo.A foo= new Foo.A();
foo.TheFooString = "I'm from Foo.A";
string xml_foo = foo.ToXmlString();
Bar.A bar = Bar.A.Deserialize( xml_foo );