Reputation: 8392
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
Upvotes: 2
Views: 1518
Reputation: 57946
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)));
Upvotes: 2
Reputation: 10397
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));
Upvotes: 1
Reputation:
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...
Upvotes: 2