How To Define Guid Properties in XSD Schemas for Generating POCO Classes

I have been taking a bit of a “schema first” development approach by using xml schema files (.xsd) for generating POCO classes using tools such as xsd.exe and xsd2code. I wanted to define a class in the XSD schema file that would have a Guid property. There were no examples on how to do this, but I found out that it can be done using a little bit of reverse engineering.

I wondered what schema xsd.exe would generate from an assembly containing a class having a Guid property. To find out, I created a new class library property and defined single POCO class containing a Guid property. I then ran xsd.exe on the compiled assembly to see what I would get for the generated xsd schemas. Here is the class.

using System;

namespace XmlSerializeExample
{
    public class Person
    {
        public Guid ID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}

Maybe the Guid property would map to just a simple old string property, but instead, this schema file was generated. I used the following command line for xsd.exe:

xsd.exe -t:XmlSerializeExample.Person XmlSerializeExample.dll

This gave me two files, schema0.xsd and schema1.xsd.

schema0.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:import namespace="http://microsoft.com/wsdl/types/" />
  <xs:element name="Person" nillable="true" type="Person" />
  <xs:complexType name="Person">
    <xs:sequence>
      <xs:element minOccurs="1" maxOccurs="1" name="ID" xmlns:q1="http://microsoft.com/wsdl/types/" type="q1:guid" />
      <xs:element minOccurs="0" maxOccurs="1" name="FirstName" type="xs:string" />
      <xs:element minOccurs="0" maxOccurs="1" name="LastName" type="xs:string" />
      <xs:element minOccurs="1" maxOccurs="1" name="Age" type="xs:int" />
    </xs:sequence>
  </xs:complexType>
</xs:schema>

schema1.xsd

<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:tns="http://microsoft.com/wsdl/types/" elementFormDefault="qualified" targetNamespace="http://microsoft.com/wsdl/types/" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:simpleType name="guid">
    <xs:restriction base="xs:string">
      <xs:pattern value="[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}" />
    </xs:restriction>
  </xs:simpleType>
</xs:schema>

Now it seems like I was getting somewhere, the schema1.xsd files defines the guid type in the http://microsoft.com/wsdl/types/ namespace. So all we need to do is to reference this schema to get our Guid.

I created an example Widget class in an xml schema:

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="Widget"
    targetNamespace="http://tempuri.org/Widget.xsd"
    elementFormDefault="qualified"
    xmlns="http://tempuri.org/Widget.xsd"
    xmlns:mstns="http://tempuri.org/Widget.xsd"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
>
  <xs:import namespace="http://microsoft.com/wsdl/types/" schemaLocation="schema1.xsd" />

  <xs:element name="Widget" nillable="true" type="Widget" />
  <xs:complexType name="Widget">
    <xs:sequence>
      <xs:element minOccurs="1" maxOccurs="1" name="ID" xmlns:q1="http://microsoft.com/wsdl/types/" type="q1:guid" />
      <xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
      <xs:element minOccurs="0" maxOccurs="1" name="Descritption" type="xs:string" />
    </xs:sequence>
  </xs:complexType>

</xs:schema>

Using the xsd2code add-in for Visual Studio 2010, I was able to generate the following:

// ------------------------------------------------------------------------------
//  <auto-generated>
//    Generated by Xsd2Code. Version 3.5.0.27515
//    <NameSpace>XmlSerializeExample</NameSpace><Collection>List</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>False</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>False</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>False</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>False</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>False</ExcludeIncludedTypes><EnableInitializeFields>True</EnableInitializeFields>
//  </auto-generated>
// ------------------------------------------------------------------------------
namespace XmlSerializeExample
{
    using System;
    using System.Diagnostics;
    using System.Xml.Serialization;
    using System.Collections;
    using System.Xml.Schema;
    using System.ComponentModel;
    using System.Collections.Generic;


    [System.Diagnostics.DebuggerStepThroughAttribute()]
    public partial class Widget
    {

        private System.Guid idField;

        private string nameField;

        private string descritptionField;

        public System.Guid ID
        {
            get
            {
                return this.idField;
            }
            set
            {
                this.idField = value;
            }
        }

        public string Name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        public string Descritption
        {
            get
            {
                return this.descritptionField;
            }
            set
            {
                this.descritptionField = value;
            }
        }
    }
}

We now have a way to define Guid properties in the .xsd schemas.

Download PDF
This entry was posted in XML and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *