C # serialization xsi: type and xsd

I have a circuit defined as follows:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Books" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="Books" msdata:IsDataSet="true" msdata:Locale="en-US">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Book" type="MyBookType"></xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>

  <xs:complexType name="MyBookType">
  ...
  </xs:complexType>

</xs:schema>

Using this scheme and xsd.exe, I generate classes that will be used during serialization. The class generated by the above schema generates the following xml when serialized:

<Books>
  <Book>
  ...
  </Book>
</Books>

This xml is used in the SOAP request, and the service on the other end expects the following xml:

<Books>
  <Book xsi:type="MyBookType">
  ...
  </Book>
</Books>

How can I change my schema so that the xsi: type attribute is included in serialized xml?

+5
source share
1 answer

Use a derived type and attribute XmlInclude. For instance:

public class Book
{
    public string Title;
    public string Author;
}

public class MyBookType : Book { }

[XmlInclude(typeof(MyBookType))]
[XmlRoot("Books")]
public class Books : List<Book> { }

public void Run()
{
    var b =  new Books();
    b.Add(new MyBookType
        {
            Title = "The Art of War",
            Author = "Sun Tzu"
        });
    b.Add(new MyBookType
        {
            Title = "Great Expectations",
            Author = "Charles Dickens"
        });

    var s = new XmlSerializer(typeof(Books));
    s.Serialize(Console.Out, b);
}

Doing this produces this output:

<?xml version="1.0" encoding="IBM437"?>
<Books xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Book xsi:type="MyBookType">
    <Title>The Art of War</Title>
    <Author>Sun Tzu</Author>
  </Book>
  <Book xsi:type="MyBookType">
    <Title>Great Expectations</Title>
    <Author>Charles Dickens</Author>
  </Book>
</Books>

SOAP-, ASMX, , . [XmlInclude] , . , -.

XmlInclude, XSD WSDL, XSD, , #.

WSDL Books, Book. a MyBookType, , .

+5

All Articles