Reputation: 17408
I use this:
[http://xmltocsharp.azurewebsites.net/][1]
to create some classes from some XML. Sometimes the translation suggests:
[XmlElement(ElementName="sup")]
public List<string> Sup { get; set; }
and sometimes:
[XmlElement(ElementName = "sup")]
public Sup Sup { get; set; } }
Can I make my deserialisation class more robust to cope with both situations?
PS:
Using this:
[XmlElement(ElementName= "sub")]
public List<Sub> Sub { get; set; }
[XmlElement(ElementName = "sup")]
public List<Sup> Sup { get; set; }
made everything more robust
Upvotes: 1
Views: 50
Reputation: 1549
See this I have created Example for you this both XML will be handled with my given model
Simply Use Parent of all That is List of the object if we are getting string still it will take and if the list of strings then also and same for an object if its single object or multiple All problem will be solved I guess
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Hello</heading>
<heading>Hello2</heading>
<body>Don't forget me this weekend!</body>
</note>
<note>
<to>Tove</to>
<from>Jani</from>
<heading><subhead>Data</subhead></heading>
<body>Don't forget me this weekend!</body>
</note>
[XmlRoot(ElementName = "note")]
public class Note
{
[XmlElement(ElementName = "to")]
public string To { get; set; }
[XmlElement(ElementName = "from")]
public string From { get; set; }
[XmlElement(ElementName = "heading")]
public List<object> Heading { get; set; }
[XmlElement(ElementName = "body")]
public string Body { get; set; }
}
Whole Tested Example:-
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string data = File.ReadAllText("D://pleasecheckXML.txt");
XmlSerializer xmldata = new XmlSerializer(typeof(Note));
byte[] byteArray = Encoding.ASCII.GetBytes(data);
MemoryStream stream = new MemoryStream(byteArray);
var datafromxml = xmldata.Deserialize(stream);
}
}
[XmlRoot(ElementName = "note")]
public class Note
{
[XmlElement(ElementName = "to")]
public string To { get; set; }
[XmlElement(ElementName = "from")]
public string From { get; set; }
[XmlElement(ElementName = "heading")]
public List<object> Heading { get; set; }
[XmlElement(ElementName = "body")]
public string Body { get; set; }
}
}
Upvotes: 1