How can I validate an in-memory schema XML file with .NET?
3 answers
Here's mine:
public static bool IsValid(XElement element, params string[] schemas)
{
XmlSchemaSet xsd = new XmlSchemaSet();
XmlReader xr = null;
foreach (string s in schemas)
{
xr = XmlReader.Create(new MemoryStream(Encoding.Default.GetBytes(s)));
xsd.Add(null, xr);
}
XDocument doc = new XDocument(element);
var errored = false;
doc.Validate(xsd, (o, e) => errored = true);
return !errored;
}
And you can use it:
var xe = XElement.Parse(myXmlString); //by memory; may be wrong
var result = IsValid(xe, MyApp.Properties.Resources.MyEmbeddedXSD);
This is not a guarantee that it is 100%; it's just a good starting point for you. XSD validation is not something I'm completely prepared for ...
+2
source to share
Find out how it is done in Winter4NET. Full source code here . Original code excerpt:
Stream GetXsdStream() {
string name = this.GetType().Namespace + ".ComponentsConfigSchema.xsd";
return Assembly.GetExecutingAssembly().GetManifestResourceStream( name );
}
...
XmlSchema schema = XmlSchema.Read( GetXsdStream(), null);
xmlDoc.Schemas.Add( schema );
xmlDoc.Validate(new ValidationEventHandler(ValidationCallBack));
+1
source to share