Phani

Phani

  • NA
  • 1
  • 0

validating xml using XSD in C#

Jun 11 2009 8:10 AM

Hi,
   I am trying to validate an xml file using xsd. I wantedly missed an attribute in xml file which is mandatory, but the xsd validation is not throwing any error.
here is my code. C#:
 public string[] Validate(string xml, XmlSchemaSet schemas) 
{
_validationErrors.Clear();XmlReaderSettings xsettings = new XmlReaderSettings();
xsettings.Schemas.Add(schemas);xsettings.ValidationType = ValidationType.Schema;
xsettings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints;xsettings.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;xsettings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings;
xsettings.ValidationEventHandler += XmlValidationEventHandler;using (StringReader sreader = new StringReader(xml))
{using (XmlReader xreader = XmlReader.Create(sreader, xsettings))
{while (xreader.Read()) ;
}
}return _validationErrors.ToArray();
}
 void XmlValidationEventHandler(object sender, ValidationEventArgs e)
{if (e.Severity == XmlSeverityType.Error)
{
_validationErrors.Add(e.Message);
}
}

Xml Data:
 <?xml version="1.0" encoding="utf-8"?> 
<
Envelope><Client LastName="Williams"> </Client>
<
Client LastName="Irwin"> </Client>
</
Envelope>

XSD:
 <?xml version="1.0" encoding="utf-8" ?> 
<
xsd:schema id="CRMExport" attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:dt="http://distribution-technology.com" targetNamespace="http://distribution-technology.com" >
<
xsd:element name="Envelope"><xsd:complexType>
<
xsd:sequence><xsd:element minOccurs="1" maxOccurs="2" name="Client">
<
xsd:complexType><xsd:attribute name="FirstName" type="xsd:string" use="required" />
<
xsd:attribute name="LastName" type="xsd:string" use="required" /></xsd:complexType>
</
xsd:element></xsd:sequence>
</
xsd:complexType></xsd:element>
</
xsd:schema>
 

 
When I execute the application, the xsd should return an error after validation as I did not supplied Firstname attribute of client in the xml.
But here it is not throwing any error, could you please tell me if the error is in the configuration of XSD on anything else?
 
Thanks in advance,
Phaniraj