This is my validation code:
public class XMLValidator
{
// Validation Error Count
static int ErrorsCount = 0;
// Construct a validation error message
static string ErrorMessage = "";
private static void ValidationHandler(object sender,
ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error || e.Severity ==
XmlSeverityType.Warning)
{
ErrorsCount++;
ErrorMessage += String.Format(ErrorsCount + ". Line {0},
Position {1} \"{2}\"",
e.Exception.LineNumber, e.Exception.LinePosition,
e.Exception.Message) + "\r\n";
}
}
public String Validate(string XMLDoc, string XSDSchema)
{
String ValidationMessage = null;
// Create the XmlSchemaSet class
XmlSchemaSet sc = new XmlSchemaSet();
// Add the schema to the collection
sc.Add(null, XSDSchema);
// Set the validation settings
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.Schemas = sc;
settings.ValidationEventHandler += new ValidationEventHandler
(ValidationHandler);
settings.ValidationFlags =
XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation;
settings.CloseInput = true;
// Create the XmlReader object
XmlReader reader = XmlReader.Create(XMLDoc, settings);
// Parse the file
while (reader.Read()) ;
if (ErrorsCount > 0)
{
// XML validation failed
ValidationMessage = ErrorMessage;
}
return ValidationMessage;
}
}
[quoted text, click to view] "Martin Honnen" wrote:
> Eve wrote:
> > The xsd I'm using is rather complex, I didn't write it, it's third party and
> > I prefer not to dig deep into it. I just need to get a general idea of how
> > xsd works, specifically if it's possible for xsd to "prevent" xml from having
> > an element in the wrong place, which according to what you wrote, Martin
> > ("You can certainly specify which child elements are allowed on a certain
> > element" - this is exactly what I mean when I say, "xsd to impose specific
> > XPath"). If that's the case, why don't I get any errors if I specify a child
> > element that is invalid? Again:
> > OrderPartners/Partner is correct
> > OrderProperties/Partner is not
>
> How do you validate exactly? Do you use an XML editor? If so which one?
> Or do you use an API, which one exactly?
> Have you tried a different editor or parser to check whether the
> validation problem is occuring there too?
>
>
> --
>
> Martin Honnen --- MVP XML
>
http://JavaScript.FAQTs.com/