代码之家  ›  专栏  ›  技术社区  ›  simendsjo

使用xmlclude..的多态元素类型名。。?

  •  3
  • simendsjo  · 技术社区  · 15 年前

    我想创建一个结构,如:

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

    如果我使用XmlType属性,我可以更改xsi:type name,但不是名称标签。

    1 回复  |  直到 15 年前
        1
  •  11
  •   Quartermeister    15 年前

    你在找什么 XmlArrayItemAttribute

    [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