gpt4 book ai didi

c# - 将 XML 字符串转换为 List 而无需在 C# 中指定元素根

转载 作者:数据小太阳 更新时间:2023-10-29 02:33:36 24 4
gpt4 key购买 nike

我需要将 XML 字符串转换为 List,该方法应该是通用的。我写了一个方法,但它没有按预期执行。

场景:#1

模型类:

public class Employee {
public int EmpId { get; set; }
public string Name { get; set; }
}

XML:

<EmployeeList
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Employee>
<EmpId>1</EmpId>
<Name>Emma</Name>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>Watson</Name>
</Employee>
</EmployeeList>

场景:#2

模型类:

public class Person {
public int PersonId { get; set; }
public string Name { get; set; }
}

XML:

<PersonList
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<PersonId>1</EmpId>
<Name>Emma</Name>
</Person>
<Person>
<PersonId>2</EmpId>
<Name>Watson</Name>
</Person>
</PersonList>

我需要一种通用方法将上述 XML 转换为 List<Employee>List<Person> .

我使用了下面的代码

public static T[] ParseXML<T>(this string @this) where T : class {
var reader = XmlReader.Create(@this.Trim().ToStream(),new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Document });
return new XmlSerializer(typeof(T[])).Deserialize(reader) as T[];
}

但我得到了 NULL .请帮助我如何处理这个问题。

我引用了很多代码,但它们告诉我将根元素指定为硬编码值。但我需要一个通用方法。

签名应该是

public static T[] ParseXML<T>(this string @this) where T : class { }

请在这方面帮助我。

最佳答案

默认的根名称是 ArrayOfThing , 不是 ThingList ,所以你需要告诉序列化程序:

var ser = new XmlSerializer(list.GetType(), new XmlRootAttribute("EmployeeList"));

但是,您还需要缓存并重新使用它以防止程序集内存泄漏(只有最基本的构造函数会自动缓存)。泛型上的静态只读字段是一个不错的选择,例如:

static class SerializerCache<T> {
public static readonly XmlSerializer Instance = new XmlSerializer(
typeof(List<T>), new XmlRootAttribute(typeof(T).Name + "List"));
}

然后使用 SerializerCache<T>.Instance而不是 new XmlSerializer

如果你愿意,显然可以交换列表和数组......

关于c# - 将 XML 字符串转换为 List<T> 而无需在 C# 中指定元素根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43871038/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com