views:

157

answers:

3

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

Thanks in advance

+2  A: 

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)));
Rubens Farias
thank you, I figured out how to implement the "... your resource stream here..." and now it works
marco.ragogna
how can I improve this answer, marco?
Rubens Farias
I thinks is ok, but probably you can describe or add a link how to retrieve an embedded resource file from an assembly
marco.ragogna
done; hope it helps!
Rubens Farias
+1  A: 

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 by:

var xe = XElement.Parse(myXmlString); //by memory; may be wrong
var result = IsValid(xe, MyApp.Properties.Resources.MyEmbeddedXSD);

This isn't a guarantee that this is 100%; its just a good starting point for you. XSD validation isn't something I'm completely up on...

Will
+1  A: 

Check out how it is done in Winter4NET. The full source code is here. The essential 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));
thorn