我有一个包含如下列表的 xml 文件:
<TestFile>
<string>Foo</string>
<bool>false</bool>
<bool>true</bool>
<string>Bar</string>
</TestFile>
我想将它反序列化为“值”类型的数组。该类型有两个子类型“ValueString”和“ValueBool”:
[XmlRoot("TestFile")]
public class TestFile
{
public List<Test> Tests;
}
public class Value
{
}
public class ValueString : Value
{
[XmlText]
public string Value;
}
public class ValueBool : Value
{
[XmlText]
public bool Value;
}
我不知道该怎么做。我试过 XmlIncludeAttributes 但这还不够,因为元素名称与类名称不匹配。我已经尝试过 XmlChoiceIdentifier,但是我发现的示例在我调整它们时无法编译...
我需要保留元素的顺序,因此将元素分成两个列表是行不通的。我也无法更改 xml 结构,因为它来自外部源。显然这只是一个例子 - 我的真实类型更复杂......
最佳答案
我终于找到了解决方案:
[XmlRoot("TestFile")]
public class TestFile
{
[XmlElement(ElementName = "string", Type = typeof(ValueString))]
[XmlElement(ElementName = "bool", Type = typeof(ValueBool))]
public List<Test> Tests;
}
我想我以前试过...好吧,至少现在可以了。此示例还有另一个问题:您不能将 bool 字段映射到元素文本,但无论如何在我的真实场景中都不存在该特定问题...
关于c# - xml 元素列表到公共(public)基类型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5621018/