C# – how to find restriction values in a simple xsd element with c#

cxmlxsd

How can I retrieve these enumeration types on an xsd simpleType with c#? Here is a sample simple type?

<xs:simpleType name="PaymentType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="Cash" />
      <xs:enumeration value="CreditCard" />
  </xs:restriction>
</xs:simpleType>

thank you

Best Answer

You could look at using the Schema Object Model (SOM) as in this code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Schema;

namespace Testing.Xml
{
    class Program
    {
        static void Main(string[] args)
        {
            // read the schema
            XmlSchema schema;
            using (var reader = new StreamReader(@"c:\path\to\schema.xsd"))
            {
                schema = XmlSchema.Read(reader, null);
            }

            // compile so that post-compilation information is available
            XmlSchemaSet schemaSet = new XmlSchemaSet();
            schemaSet.Add(schema);
            schemaSet.Compile();

            // update schema reference
            schema = schemaSet.Schemas().Cast<XmlSchema>().First();

            var simpleTypes = schema.SchemaTypes.Values.OfType<XmlSchemaSimpleType>()
                                               .Where(t => t.Content is XmlSchemaSimpleTypeRestriction);

            foreach (var simpleType in simpleTypes)
            {
                var restriction = (XmlSchemaSimpleTypeRestriction) simpleType.Content;
                var enumFacets = restriction.Facets.OfType<XmlSchemaEnumerationFacet>();

                if (enumFacets.Any())
                {
                    Console.WriteLine("" + simpleType.Name);
                    foreach (var facet in enumFacets)
                    {
                        Console.WriteLine(facet.Value);
                    }
                }
            }
        }
    }
}

This code only works for named simple types though - if you have elements or attributes that contain anonymous simple types then it gets a lot more complicated as you have to walk all the elements and attributes to find simple types that have restriction content with enumeration facets.