gpt4 book ai didi

c# - 尝试将 xml 数组反序列化为具有子类的 C# 类

转载 作者:行者123 更新时间:2023-11-30 14:50:48 26 4
gpt4 key购买 nike

我有一个简单的例子,是我从我的真实代码中提炼出来的。问题是只要我能够在类层次结构中显式分配类型,我就可以在下面创建一个 C# 类。但是,我的面板数组不会创建子类 TwoColumnPanel。相反,我在面板列表中只得到一个面板。

[TestMethod]
public void XmlRepoCreatesTestRepo()
{
object obj;
using (XmlReader reader = XmlReader.Create(new StringReader(TestXml)))
{
reader.MoveToContent();
switch (reader.Name)
{
case "TestRepo":
obj = new XmlSerializer(typeof(TestRepo)).Deserialize(reader);
break;
default:
throw new NotSupportedException("Unexpected: " + reader.Name);
}
}
}

public string TestXml = @"<TestRepo>
<Name>Wandercoder Was Here</Name>
<Page>
<Panel>
<ColumnAttribute>1</ColumnAttribute>
</Panel>
<TwoColumnPanel>
<ColumnAttribute>2</ColumnAttribute>
</TwoColumnPanel>
<Panels>
<Panel>
<ColumnAttribute>1</ColumnAttribute>
</Panel>
<TwoColumnPanel>
<ColumnAttribute>2</ColumnAttribute>
</TwoColumnPanel>
</Panels>
</Page>
</TestRepo>";
}

[DataContract]
[Serializable]
public class TestRepo
{
[DataMember]
public string Name { get; set; }
[DataMember]
public Page Page { get; set; }
}
[DataContract]
[Serializable]
public class Page
{
//This works.
[DataMember]
public Panel Panel { get; set; }
//This works, too.
[DataMember]
public TwoColumnPanel TwoColumnPanel { get; set; }
//For this one, however, I only get the one Panel when I deserialize.
//Why doesn't it properly deserialize the TwoColumnPanel specified in the xml above.
[DataMember]
public List<Panel> Panels { get; set; }
}
[DataContract]
[Serializable]
public class Panel
{
[DataMember]
public int ColumnAttribute { get; set; }
}
[DataContract]
[Serializable]
[XmlRoot("Panel")]
public class TwoColumnPanel : Panel
{
public TwoColumnPanel()
{
ColumnAttribute = 2;
}
}

最佳答案

[DataContract]
[Serializable]
public class Page
{
//This works.
[DataMember]
public Panel Panel { get; set; }
//This works, too.
[DataMember]
public TwoColumnPanel TwoColumnPanel { get; set; }
//For this one, however, I only get the one Panel when I deserialize.
//Why doesn't it properly deserialize the TwoColumnPanel specified in the xml above.
[DataMember]
[XmlArray("Panels")]
[XmlArrayItem("TwoColumnPanel", typeof(TwoColumnPanel))]
[XmlArrayItem("Panel", typeof(Panel))]
public List<Panel> Panels { get; set; }
}

关于c# - 尝试将 xml 数组反序列化为具有子类的 C# 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35855443/

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