问题
All the C#
codes available over net are just for read and loading XML
and XSD
.
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(@"D:\XML\Sample.xml");
xmlDocument.Schemas.Add("http://www.w3.org/2001/XMLSchema", @"D:\XML\Sample.xsd");
xmlDocument.Schemas.Compile();
ValidationEventHandler eventhandler = new ValidationEventHandler(ValidationEventHandler);
xmlDocument.Validate(eventhandler);
if (valid == true)
{
label1.Text = "Xml Got Validated!!";
}
void ValidationEventHandler(object sender, ValidationEventArgs e)
{
valid = false;
switch (e.Severity)
{
case XmlSeverityType.Error: label1.Text = "Xml Validation Failed".ToString();
break;
case XmlSeverityType.Warning: label1.Text = "Xml Has some warning".ToString();
break;
}
}
This actually is not validating my XML
just reading even if I don't pass elements that are mandatory it says: "ITS Valid"
回答1:
I use the following and it applies validation successfully:
var xsd = new XmlSchemaSet();
using (var ms = new StringReader(Resources.MyXsd))
{
using (var reader = XmlReader.Create(ms))
{
xsd.Add(XmlSchema.Read(reader, delegate { }));
}
}
var document = XDocument.Parse(text);
document.Validate(
xsd, (o, e) =>
{
if (e.Severity == XmlSeverityType.Error)
{
validationMessages.Add(e.Exception.Message);
}
}
);
来源:https://stackoverflow.com/questions/6522319/how-to-validate-xml-against-xsd-in-c-sharp-windows-forms