简体   繁体   English

XML 文件中不同类的反序列化

[英]XML deserialization of different classes in file

I get a file with different content (currently 4 different classes), either我得到一个内容不同的文件(目前有 4 个不同的类),要么

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

or或者

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

or...或者...

At time of parsing I have no further information which class is in the file.在解析时,我没有进一步的信息 class 在文件中。

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... ClassB等也是如此……

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.我可以为所有类提供相同的基础 class,尽管它们的形式完全不同。

I solved this issue with XmlSerializer.CanDeserialize(XmlReader)我用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");
            }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM