我想创建一个像这样的结构:
<root>
<items>
<myns:a s="a"/>
<b s="a"/>
</items>
</root>
根中的项目是公共(public)基类的后代。我就是无法让它工作。以下代码段创建
<root>
<items>
<Base xsi:type="A" s="a"/>
<Base xsi:type="B" s="a"/>
</items>
</root>
[Serializable]
[XmlInclude(typeof(A))]
[XmlInclude(typeof(B))]
public class Base
{
}
[Serializable]
public class A : Base
{
public string a = "a";
}
[Serializable]
public class B : Base
{
public string b = "b";
}
[Serializable]
public class Root
{
public List<Base> items = new List<Base>();
}
如果我使用 XmlType 属性,我可以更改 xsi:type 名称,但不能更改名称标签。 我还想在其中一个标签上使用自定义命名空间,但是如果我将命名空间添加到 XmlType,我会收到一条错误消息,指出无法找到该类型,并且必须添加 XmlInclude..
我想这其实很简单,我只是不知道如何......
最佳答案
[Serializable]
public class Root
{
[XmlArrayItem("a", typeof(A), Namespace = "myns")]
[XmlArrayItem("b", typeof(B))]
public List<Base> items = new List<Base>();
}
这将序列化为:
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<items>
<a xmlns="myns">
<a>a</a>
</a>
<b>
<b>b</b>
</b>
</items>
</Root>
你也可以使用 XmlElementAttribute如果您希望项目是 Root 的直接子级而不是项目的元素。
关于c# - 使用 XmlInclude 的多态元素类型名称..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3512019/