Skip to main content
 首页 » 编程设计

c#之xml 元素列表到公共(public)基类型的数组

2024年02月23日15freeliver54

我有一个包含如下列表的 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 字段映射到元素文本,但无论如何在我的真实场景中都不存在该特定问题...