This will deserialize an xml sample into the "XmlModel" class.
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace XmlTest
{
public class DeserializeXml
{
public XmlModel GetXmlModel()
{
string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<root>
<foo>
<bar>1</bar>
<bar>2</bar>
</foo>
</root>";
var dS = new XmlSerializer(typeof(XmlModel));
var m = new XmlModel();
using (var reader = new StringReader(xml))
{
return (XmlModel) dS.Deserialize(reader);
}
}
}
[XmlRoot("root")]
public class XmlModel
{
[XmlArray("foo")]
[XmlArrayItem("bar")]
public List<string> Foo { get; set; }
}
}
This will get the model:
var d = new DeserializeXml();
result = d.GetXmlModel();
I am working with legacy code and I cannot make changes to the XmlModel class other than changing the XmlAttributes. Here is the problem: the actual Xml has no "foo" node:
string xml = @"<?xml version=""1.0"" encoding=""utf-16""?>
<root>
<bar>1</bar>
<bar>2</bar>
</root>";
So now I am stuck with the task of making the deserializer swallow this xml and output type XmlModel. Is this possible without Xslt preprocessing or other more complicated methods?