1

I have a lot of XML files and unfortunately no XML schema or any other source of description. So I must generate c# classes based on specific XML file. Problem is that those files have complex structure and they differ between themselves. Is it possible for XmlSerializer to throw exception when it runs into unexpected element?

For example:

[XmlRoot(ElementName = "team"]
public class Team
{
[XmlElement(ElementName = "player"]
public List<Player> Players { get; set; }
[XmlElement(ElementName = "coach"]
public Coach Coach { get; set; }
}

<team>
    <player></player>
    <player></player>
    <coach></coach>
    <unexpectedElement></unexpectedElement>
</team>

Element <unexpectedElement> is not defined in Team class so it should be considered invalid. Is there any solution to such problem?

drv
  • 125
  • 1
  • 10
  • You can use the msdn xsd.exe tool to generate classes from the xml instead of a schema. – jdweng May 23 '18 at 10:51
  • I know that. But there are over hundred of XML files and they have slightly different structure as I said above. – drv May 23 '18 at 10:57
  • It depends on how similar they are. You can parse the xml using xml linq (XDocument) which give lots of latitude. I often put results into a dictionary so when xml varies the code still will work. – jdweng May 23 '18 at 11:04
  • 2
    Subscribe `XmlSerializer` to [UnknownElement](https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.unknownelement(v=vs.110).aspx) event. – Alexander Petrov May 23 '18 at 13:10
  • Yes, it seems to work. I didn't know that something like this exists. Thanks! – drv May 23 '18 at 14:08
  • OK, so duplicate of [Unknown elements are just ignored during deserialization](https://stackoverflow.com/q/49914172/3744182) then? – dbc May 23 '18 at 16:09

0 Answers0