C# 反序列化XMLto对象数组或单个对象

C# 反序列化XMLto对象数组或单个对象,c#,xml,xml-serialization,xml-deserialization,C#,Xml,Xml Serialization,Xml Deserialization,我试图编写一个通用方法,用于将xml反序列化为对象数组 给定看起来是这样的XML: <people> <person> <someElement>content</someElement> </person> <person> <someElement>more content</someElement> </person>

我试图编写一个通用方法,用于将xml反序列化为对象数组

给定看起来是这样的XML:

<people>
    <person>
        <someElement>content</someElement>
    </person>
    <person>
        <someElement>more content</someElement>
    </person>
</people>
这将按预期工作,并返回带有2个条目的
person[]

但是,在我使用的API中,如果只返回1个结果,它只返回:

<person>
    <someElement>content</someElement>
</person>

内容
我的反序列化失败了<代码>人员[]保持为空

有什么想法可以实现这一点吗

编辑
我正在考虑在两者之间运行XSLT,并将
T
的名称传入,如果它与根节点匹配,则添加一个包装节点?

检查根元素的名称,如果它不是
people
,则将其添加到xml中,一切都会正常进行


更新: 检查xml文档的深度,如果其==2,则创建根元素。 另一种方法-使用LINQ-TO-XML
XElement.Descandants(“person”)
-person-elements的数组

我最终使用XSLT来确保我所跟踪的节点不是根节点

基本上,我有一个XSLT文件,其中包含:

<xsl:template match="/">
    <rootNode>
        <xsl:apply-templates select="node()|@*"/>
    </rootNode>
</xsl:template>

你是说在这种情况下没有
people
根节点?需要一种方法来处理这个问题。发布的示例只是一个例子,有超过100种不同的xml类型。无法检查深度,因为实际数据可能有很多深度,使用L2Xml检查特定节点也不是通用的。
<xsl:template match="/">
    <rootNode>
        <xsl:apply-templates select="node()|@*"/>
    </rootNode>
</xsl:template>
//using reflection to look what the XmlType has been declared on this type
var typeAttributes = Attribute.GetCustomAttribute(typeof(T), typeof(XmlTypeAttribute));

//determine an xpath query to find this type of elements parent
string xPathtoTypeName = string.Format("//{0}/parent::node()", ((XmlTypeAttribute)typeAttributes).TypeName);

//use the above xpath query to find the parent node.
var parentNode = transformedDocument.SelectSingleNode(xPathtoTypeName);

//deserialize as before
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T[]), new XmlRootAttribute(parentNode.Name));
XmlNodeReader nodeReader = new XmlNodeReader(parentNode);
results = xmlSerializer.Deserialize(nodeReader) as T[];