C# 使用XmlInclude..的多态元素类型名。。?

C# 使用XmlInclude..的多态元素类型名。。?,c#,.net,xml-serialization,C#,.net,Xml Serialization,我想创建一个结构,如: <root> <items> <myns:a s="a"/> <b s="a"/> </items> </root> 其中根目录中的项是公共基类的后代。我就是不能让它工作。下面的代码段创建 <root> <items> <Base xsi:type="A" s="a"/> <Base xsi:type="B" s="a"/>

我想创建一个结构,如:

<root>
 <items>
  <myns:a s="a"/>
  <b s="a"/>
 </items>
</root>

其中根目录中的项是公共基类的后代。我就是不能让它工作。下面的代码段创建

<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>();
}

[可序列化]
[xmlclude(类型(A))]
[xmlclude(typeof(B))]
公共阶级基础
{
}
[可序列化]
公共A类:基本类
{
公共字符串a=“a”;
}
[可序列化]
B类公共服务:基本服务
{
公共字符串b=“b”;
}
[可序列化]
公共类根
{
公共列表项=新列表();
}
如果使用XmlType属性,则可以更改xsi:type名称,但不能更改name标记。 我还想在其中一个标记上使用自定义名称空间,但如果我将名称空间添加到XmlType,则会收到一条错误消息,指出找不到该类型,必须添加XmlInclude

我想这其实很简单,我就是不知道你在找什么

[可序列化]
公共类根
{
[XmlArrayItem(“a”,typeof(a),Namespace=“myns”)]
[XmlArrayItem(“b”,类型为(b))]
公共列表项=新列表();
}
这将序列化为:

<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>


如果希望项是根的直接子项,而不是具有项的元素

很好!不知道我使用了几个XmlArrayItem。这还允许我从基类中删除XmlInclude。谢谢这正是我要找的!
<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>