C# 无法将 xml 反序列化为 return 通用列表

C# Can't deserialize xml to return a generic List

我尝试从 xml 文件加载列表。我有不同的自定义列表 类 和不同的 xml 文件。计划是创建一种方法能够像这样反序列化所有这些:

ListDependencies.Deserialize(DependenciesPath);
ListProfessions.Deserialize(ProfessionsPath);
ListCategories.Deserialize(CategoriesPath);
...

反序列化时出现 xml 文件格式意外的错误。

    public static List<T> Deserialize<T>(this T value, string _path)
    {
        var xmlserializer = new XmlSerializer(typeof(List<T>));

        using (StreamReader sr = new StreamReader(_path, Encoding.Unicode))
        {
            using (var reader = XmlReader.Create(sr.BaseStream))
            {
                return (List<T>)xmlserializer.Deserialize(reader);
            }
        }
    }

内部异常:

{"<ArrayOfDependencyObject xmlns=''> was not expected."} System.Exception {System.InvalidOperationException}

XmlContent:

<ArrayOfDependencyObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <DependencyObject>
    <Profession>80dd893e-9eb6-42c6-9b60-a61b87df0d1b</Profession>
    <Dependency>f76c72be-f2da-435b-b1f8-a4775c0bc1f1</Dependency>
  </DependencyObject>
  <DependencyObject>
    <Profession>8ab9b108-dd4b-4639-b323-c7a6c28f1314</Profession>
    <Dependency>9b86ff1d-c1de-4f95-adc8-413a94714cc0</Dependency>
  </DependencyObject>
  <DependencyObject>
    <Profession>5a273efa-eb29-4ea0-bd1d-2bb84727aa1e</Profession>
    <Dependency>954bd3d6-e78e-424e-bd69-8b46f239c5f2</Dependency>
  </DependencyObject>
</ArrayOfDependencyObject>

谁能帮帮我?

我从 XML 中看到的是一个包含元素数组的对象。如下更改Deserialize方法并重试

public static T Deserialize<T>(this T value, string _path)
{
    var xmlserializer = new XmlSerializer(typeof(T));

    using (StreamReader sr = new StreamReader(_path, Encoding.Unicode))
    {
        using (var reader = XmlReader.Create(sr.BaseStream))
        {
            return (T)xmlserializer.Deserialize(reader);
        }
    }
}

我已经用给定的 XML

试过这个方法
var ListDependencies = new ArrayOfDependencyObject();
var results = ListDependencies.Deserialize(xmlFile);
foreach (var element in results.DependencyObject)
{
    Console.WriteLine($"{element.Profession}:{element.Dependency}");
}

得到这个输出

80dd893e-9eb6-42c6-9b60-a61b87df0d1b:f76c72be-f2da-435b-b1f8-a4775c0bc1f1
8ab9b108-dd4b-4639-b323-c7a6c28f1314:9b86ff1d-c1de-4f95-adc8-413a94714cc0
5a273efa-eb29-4ea0-bd1d-2bb84727aa1e:954bd3d6-e78e-424e-bd69-8b46f239c5f2