How can I validate an in-memory schema XML file with .NET?

Is it possible to validate an XML file using an XSD loaded at runtime from an embedded application resource instead of using a physical file with .NET (Framework 3.5)?

Thank you in advance

+2


source to share


3 answers


You can use XmlSchemaCollection.Add(string, XmlReader)

:



string file = "Assembly.Namespace.FileName.ext";
XmlSchemaCollection xsc = new XmlSchemaCollection();
xsc.Add(null, new XmlTextReader(
    this.GetType().Assembly.GetManifestResourceStream(file)));

      

+2


source


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


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







All Articles