Donald N. Mafa
Donald N. Mafa

Reputation: 5283

Extract enumeration values from XSD file?

I am trying to extract enumeration values from an xsd file but am failing and the only code to assist is below, which only gets me the numeric value.

XSD File:

<xsd:simpleType name="PackageTypeCodeContentType">
<xsd:restriction base="xsd:token">
  <xsd:enumeration value="43">
    <xsd:annotation>
      <xsd:documentation xml:lang="en">
        <ccts:Name>Bag, super bulk</ccts:Name>
      </xsd:documentation>
    </xsd:annotation>
  </xsd:enumeration>
  <xsd:enumeration value="44">
    <xsd:annotation>
      <xsd:documentation xml:lang="en">
        <ccts:Name>Bag, polybag</ccts:Name>
        <ccts:Description>A type of plastic bag, typically used to wrap promotional pieces, publications, product samples, and/or catalogues.</ccts:Description>
      </xsd:documentation>
    </xsd:annotation>
  </xsd:enumeration>
  <xsd:enumeration value="1A">
    <xsd:annotation>
      <xsd:documentation xml:lang="en">
        <ccts:Name>Drum, steel</ccts:Name>
      </xsd:documentation>
    </xsd:annotation>
  </xsd:enumeration>...

The code I have tried using:

XmlSchema schema = XmlSchema.Read(XmlReader.Create("XsdLookups\\PackageType.xsd"), ValidationCallbackOne);
        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.Add(schema);
        schemaSet.Compile();
        var results = schema.Items.OfType<XmlSchemaSimpleType>().Where(s => (s.Content is XmlSchemaSimpleTypeRestriction) && s.Name == "PackageTypeCodeContentType").ToList();
        var enumValues = results.SelectMany(c => ((XmlSchemaSimpleTypeRestriction)c.Content).Facets.OfType<XmlSchemaEnumerationFacet>().Select(d => d.Value));
        enumValues.ToList().ForEach(p=> Debug.WriteLine(p));

I am trying to extract the name and description of the xsd documentation, e.g. "Bag, super bulk" etc

Upvotes: 0

Views: 836

Answers (1)

Donald N. Mafa
Donald N. Mafa

Reputation: 5283

Although not as elegant, I ended up using good old Xml.Linq:

XDocument schema = XDocument.Load(xsdPath);
        XNamespace xs = schema.Root?.Name.Namespace;
        var enumerations = schema
            .Root?
            .Descendants(xs + "simpleType")
            .Where(t => (string) t.Attribute("name") == simpleTypeName)
            .Descendants(xs + "enumeration")
            .ToList();
        foreach (var element in enumerations)
        {
            var annotation = element.Elements().ElementAt(0);
            var documentationElement = annotation.Elements().ElementAt(0);
            //
            var nameValue = documentationElement.Elements().ElementAt(0).Value;
            var decsValue = documentationElement.Elements().ElementAtOrDefault(1)?.Value;

            addMethod.Invoke(nameValue, decsValue);
        }

Please share if someone has a better way to do this.

Upvotes: 1

Related Questions