When we are using an XSD schema to validate an XML document, if this schema has other nested XSD schemas, if we have a myCustomType declared into the nested XSD and we don’t use XmlSchemaSet to validating the XML, we can get the error:

Type ‘myCustomType‘ is not declared

For example, if we have the myCustomType defined into MySimpleTypes.xsd and this schema was includend into another schema MyComplexTypes.xsd with:

<xs:include schemaLocation="MySimpleTypes.xsd"/>

And the MyComplexTypes.xsd schema was includend into another schema MyTypes.xsd with:

<xs:include schemaLocation="MyComplexTypes.xsd"/>

If we use XmlSchemaSet we can correctly validating an XML (even if the XSD hasn’t nested schema). XmlSchemaSet contains a cache of XML Schema definition language (XSD) schemas. So if we want to validate an XML with this schemas,  we can do like in the following example.

Supposing that xmlData object contains serializing data:

try
{ // Using StringWriter to obtain the xml string using (StringWriter sw = new StringWriter()) { // Using XmlWriter to get the serialized xmlData object using (XmlWriter xw = XmlWriter.Create(sw)) { // Serialize the object into the XmlWriter xs.Serialize(xw, xmlData); // Set the XDocument XDocument document = XDocument.Parse(sw.ToString()); // Set the xsd files path string xsdPath1 = "C:/xsd/MySimpleTypes.xsd"; string xsdPath2 = "C:/xsd/MyComplexTypes.xsd"; string xsdPath3 = "C:/xsd/MyTypes.xsd"; // Set the XmlSchemaSet with the xsd files XmlSchemaSet xss = new XmlSchemaSet(); string ns = "http://mynamespace.example.com"; xss.Add(ns, xsdPath1); xss.Add(ns, xsdPath2); xss.Add(ns, xsdPath3); // Validate the XDocument document.Validate(xss, null); } }
}
catch(Exception e)
{ // e.Message contains the error validation message
}

If we haven’t only a MyType without nested XSD;

try
{ // Using StringWriter to obtain the xml string using (StringWriter sw = new StringWriter()) { // Using XmlWriter to get the serialized xmlData object using (XmlWriter xw = XmlWriter.Create(sw)) { // Serialize the object into the XmlWriter xs.Serialize(xw, xmlData); // Set the XDocument XDocument document = XDocument.Parse(sw.ToString()); // Set the xsd file path string xsdPath = "C:/xsd/MyTypes.xsd"; // Set the XmlSchemaSet with the xsd files XmlSchemaSet xss = new XmlSchemaSet(); string ns = "http://mynamespace.example.com"; xss.Add(ns, xsdPath) // Validate the XDocument document.Validate(xss, null); } }
}
catch(Exception e)
{ // e.Message contains the error validation message }

Laisser un commentaire