0

I get a file with different content (currently 4 different classes), either

<ClassA><!-- content --></ClassA>

or

<ClassB><!-- content --></ClassB>

or ...

At time of parsing I have no further information which class is in the file.

So, currently, I try to parse by trial and error:

try
{
  ClassA result = (ClassA)new XmlSerializer(typeof(ClassA)).Deserialize(reader);
  if(!(result is null)) { \\do something }
}
catch (Exception) {}

And the same for ClassB and so on ...

Is there a more elegant way to parse the classes?

I can give all classes the same base class, although the are quite different in their form.

HarryKane
  • 129
  • 3
  • 13
  • Brute force? Read the first line and look for the appropriate name? It's kludge and horribly inelegant, but it might solve your problem – Flydog57 May 18 '21 at 18:03
  • 2
    Inherit your classes from a common ancestor. Use the XmlIncludeAttribute. – Alexander Petrov May 18 '21 at 18:44
  • 1
    You could use `XmlSerializer.CanDeserialize(XmlReader)` to check to see whether a given serializer is able to deserialize a given root element. See [How to deserialize XML if the return type could be an Error or Success object](https://stackoverflow.com/q/44234061/3744182). – dbc May 19 '21 at 04:29
  • And additional options to be found at [How to do a polymorphic deserialization in C# given a XSD?](https://stackoverflow.com/q/28086893/3744182). – dbc May 19 '21 at 14:39

1 Answers1

0

I solved this issue with XmlSerializer.CanDeserialize(XmlReader)

            using (var reader = XmlReader.Create(stream))
            {
                foreach (var type in types)
                {
                    var serializer = new XmlSerializer(type);
                    if (serializer.CanDeserialize(reader))
                    {
                        return serializer.Deserialize(reader);
                    }
                }
                throw new XmlException("Invalid xml type");
            }
HarryKane
  • 129
  • 3
  • 13