Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net XML Serialization based on an XSD?

Tags:

I've been serialising and deserialising .net objects using the XmlSerializer class without problem, however we now need somebody else to look at that data to perform some analysis on it.

In order to help with that we've produced an XSD based on our class like so: xsd.exe /t:DataClass Assembly.exe

The start of the XSD looks like this:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="DataClass" nillable="true" type="DataClass" />
  <xs:complexType name="DataClass">
    <xs:complexContent mixed="false">
      <xs:extension base="BaseDataClass">
        <xs:sequence>
          <xs:element minOccurs="0" maxOccurs="1" name="StudyID" type="xs:string" />
          <xs:element minOccurs="1" maxOccurs="1" name="Position" type="xs:int" />
          <xs:element minOccurs="1" maxOccurs="1" name="IViewer" type="xs:string" />

The XML is produced like this (where obj is an instance of our DataClass):

Dim xs As New XmlSerializer(obj.GetType)
Dim xmlTextWriter As New XmlTextWriter(memoryStream, Encoding.UTF8)
xs.Serialize(xmlTextWriter, obj)

...which produces XML looking like this:

<?xml version="1.0" encoding="utf-8"?>
<DataClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Version>SixMonthQ-E1</Version>
    <IViewer xsi:nil="true" />
    <Language xsi:nil="true" />
    ...
    <StudyID>12345</StudyID>

Bizarly, the XML produced does not adhere to the XSD generated from the same class.

My question then is, is there a way of telling the XmlSerializer to serialize the object based on a given XSD?

As an aside, I've looked at other ways of fixing this: I've tried re-generating the classes from the generated XSD - this seemed to have the same problem. I could explicitly state an ordering of elements using the XmlElement attribute, but I don't fancy doing that for 400+ public properties.

like image 283
Nik Avatar asked Oct 20 '09 10:10

Nik


1 Answers

No, sorry. It doesn't seem like there is any way for forcing XmlSerializer to take a schema into account.

Try regenerating the classes using xsd.exe and the schema it generated (doing a roundtrip conversion).

xsd.exe dataClass.xsd /classes /language:cs

At very least it might give you some insight into which aspect of the original classes the xsd.exe command had trouble with.

Also maybe try this alternative to xsd: http://xsd2code.codeplex.com/

like image 97
Josh Avatar answered Oct 05 '22 12:10

Josh