简体   繁体   中英

How to easily de-serialize polymorphic types from XML to POCOs (using XML Schema)?

Suppose I want to parse any of these XML elements:

<Server                      hostName="foobar"                      />
<WebServer                   hostName="foobar"                      />
<WebServer                   hostName="foobar" listeningOnPort="80" />
<Server xsi:type="WebServer" hostName="foobar" listeningOnPort="80" />

which adhere to the following XML Schema declarations:

<xsd:element name="Server" type="IServer" />
<xsd:element name="WebServer" substitutionGroup="Server" type="IWebServer" />

<xsd:complexType name="IServer">
  <xsd:attribute name="hostName" type="xsd:string" use="required" />
</xsd:complexType>

<xsd:complexType name="IWebServer">
  <xsd:complexContent>
    <xsd:extension base="IServer">
      <xsd:attribute name="listeningOnPort" type="xsd:int" use="optional" />
    </xsd:extension>
  </xsd:complexContent>
</xsd:complexType>

to corresponding CLR objects of these types:

class Server : IServer { .. }               // [CorrespondsTo("Server")]
class WebServer : Server, IWebServer { .. } // [CorrespondsTo("WebServer")]

interface IServer                           // [CorrespondsTo("IServer")]
{
    string HostName { get; set; }           // [CorrespondsTo("hostName")]
}

interface IWebServer : IServer              // [CorrespondsTo("IWebServer")]
{
    int? ListeningOnPort { get; set; }      // [CorrespondsTo("listeningOnPort")]
}

Is there anything in the .NET framework or any mature, lightweight XML parsing library that will achieve this without me having to write lots of code? Does having an XML Schema actually help with the XML-to-CLR type mapping?

  • A declarative solution for XML-to-CLR type mappings would be nice, eg via C# attributes.
  • Optional attributes should be transformed correctly to nullable types.
  • <Server xsi:type="WebServer" ... /> should result in a WebServer object.

.NET supports XML to CLR serialization natively.

There is a command line tool called "XSD.exe" which takes a series of .xsd documents and creates the corresponding C# objects.

http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx

Then in code, you use the XmlSerializer class to serialize and deserialize.

http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM