In C#, how to determine the XSD-defined MaxLength

2019-01-23 21:31发布

问题:

I'm using XmlReader with an attached XSD for validation.

As my XML document is being read and validated, I want to determine in my C# code the 'maxLength' value specified in the XSD for a particular element. For example, my XSD fragment is very simply defined as:

<xsd:element name="testing" minOccurs="0">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <xsd:maxLength value="10"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>

I can get the 'minOccurs' value easily using:

myReader.SchemaInfo.SchemaElement.MinOccurs;

But how do I get the 'maxLength' value (value of 10 in my example fragment above)???

I thought 'myReader.SchemaInfo.SchemaElement.Constraints' might give me this information, but that collection always has a 'Count' of zero.

Thanks,

Pat.

回答1:

you'll find here:Accessing XML Schema Information During Document Validation a good explanation of how to do this & more.



回答2:

There are ways to do so with myReader.SchemaInfo (see najmeddine's response), but in case you need to access stuff not exposed in the SchemaInfo object...

..XSD being an XML Language. You can simply load the XSD file and using XPath find the "testing" element's definition, and its maxLength.



标签: c# xsd maxlength