I am trying to figure out the correct cast type for the “Parent” property of an object of type XmlSchemaSimpleType. The below code is always returning “” as the “parent” variable is validated to null. Can anyone please help how to retrieve minOccurs from the parent of a simpleType ? Thank you!
private string GetMinOccurs(XmlSchemaSimpleType xsdSimpleType)
{
var parent = xsdSimpleType.Parent as XmlSchemaElement;
if (parent == null) return "";
return parent.MinOccurs.ToString();
}
An example of my XSD is:
<xsd:complexType name="New_Type">
<xsd:sequence>
<xsd:element name="Amount" type="Amount_Type" minOccurs="1" maxOccurs="1" />
<xsd:element name="Name" type="Name_Type" minOccurs="1" maxOccurs="1" />
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="Amount_Type">
<xsd:annotation>
<xsd:documentation>Amount</xsd:documentation>
</xsd:annotation>
<xsd:restriction base="xsd:string">
<xsd:maxLength value="12" />
</xsd:restriction>
</xsd:simpleType>
Like I said in the comment of your previous question. the
Parentproperty of anXmlSchemaSimpleTypedoes not work like you think. It looks like you are hoping it will return the<element>that has a type of theXmlSchemaSimpleTypeyou are specifying.But consider this situation:
Which would it return as there are 2 different elements with the same type? As you can see from this example, a type can be used multiple times throughout an XSD and each occurance can have a different
MinOccursvalue. If you want to get theMinOccurs, you need to find the exact<element>you want, even if the type is used just once. But to do that you need to know where it is in the XSD.This blog is a few years old, but I think helps with the point. You basically have to find the complex type using
XmlSchemaSet.GlobalTypes[], then you need to look through theParticleproperty. In your case, there will be a singleXmlSchemaSequenceobject in there (you’ll probably need to cast). Then you need to look through the items property to find yourAmountelement. From there (after another cast), you can get MinOccurs.If you don’t know exactly what you are looking for, all of the collections in the
XmlSchemaObjectproperties do haveGetEnumeratormethods, so you can useforeachto help scan everything. None are generic though so you need to do a lot of casting, but this is basically what you have to do:But this is just an example to show how to get where you want to go. You need to do some type checking before each of the casts in case it fails. For example,
var seq = (XmlSchemaSequence)((XmlSchemaComplexType)item.Value).Particle;will throw an exception after it gets to the second type in your XSD since it is not a complex type, it is a simple type.A LINQ solution might be easier if you know exactly what you want:
This method at least lets you scan the document quickly for any type that matches your
Amount_Typeand grabs the minOccurs (or returns null of there is nominOccursattribute).