简体   繁体   English

带有额外类型的 XML 反序列化会引发错误

[英]XML deserialization with extra types throws error

I do not know the type of the XML before I deserialize it.在反序列化之前,我不知道 XML 的类型。 So I'm using the overload of XmlSerializer with extraTypes .所以我将XmlSerializer的重载与extraTypes一起使用。 It does work for the first type , but it does not work for all the extraTypes .它适用于第一种type ,但不适用于所有extraTypes I'm getting the following errorMsg "System.InvalidOperationException: There is an error in XML document (1, 40). ---> System.InvalidOperationException: <Bike xmlns=''> was not expected."我收到以下错误消息"System.InvalidOperationException: There is an error in XML document (1, 40). ---> System.InvalidOperationException: <Bike xmlns=''> was not expected." . . Here's a dummy code of what I'm trying to do.这是我正在尝试做的虚拟代码。

using System;
using System.IO;
using System.Xml.Serialization;

public class Program
{
    private const string CarXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Car xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"></Car>";
    private const string BikeXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Bike xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"></Bike>";


    public static void Main(string[] args)
    {
        var xmlSerializer = new XmlSerializer(typeof(Car), new[] { typeof(Bike) });

        using (var stringReader = new StringReader(BikeXml))
        {
            try
            {
                var vehicle = (Vehicle)xmlSerializer.Deserialize(stringReader);
                Console.WriteLine(vehicle.PrintMe());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }

    }
}

public abstract class Vehicle
{
    public abstract string PrintMe();
}

public class Car : Vehicle
{
    public override string PrintMe()
    {
        return "beep beep I'm a car!";
    }
}

public class Bike : Vehicle
{
    public override string PrintMe()
    {
        return "bing bing I'm a bike!";
    }
}

Apparently the extraTypes are not meant to be used for my case.显然, extraTypes不适用于我的情况。 See msdn documentation .请参阅msdn 文档

I solved it by getting the XmlRoot.我通过获取 XmlRoot 解决了它。

public static void Main(string[] args)
{
    var xmlDocument = new XmlDocument();
    xmlDocument.LoadXml(BikeXml);
    var rootName = xmlDocument.DocumentElement.Name;
    var rootType = Type.GetType(rootName);
    var vehicle = rootType != null ? (Vehicle) Activator.CreateInstance(rootType) : null;        
    Console.WriteLine(vehicle != null ? vehicle.PrintMe() : "Error");
}

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

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