If...">

Polymorphic elements using XmlInclude ..?

I want to create a structure like:

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

If the elements in the root are descendants of a common base class. I just can't get it to work. The following snippet creates

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

If I use the XmlType attribute, I can change the type name xsi: type, but not the name tag. I also want to use my own namespace in one of the tags, but if I add a namespace in XmlType, I get an error message indicating that the type cannot be found and XmlInclude should be added.

I think this is actually quite simple, I just could not figure out how ..

+3
source share
1 answer

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, , Root .

+9

Source: https://habr.com/ru/post/1760284/


All Articles