I am writing an application that parses an Xml file. I have the schema (.xsd) file which I use to validate the Xml before trying to deserialize it:
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, "./xml/schemas/myschema.xsd");
settings.ValidationType = ValidationType.Schema;
XmlReader reader = XmlReader.Create(xmlFile, settings);
XmlDocument document = new XmlDocument();
document.Load(reader);
ValidationEventHandler eventHandler = new ValidationEventHandler(settings_ValidationEventHandler);
document.Validate(eventHandler);
Note that the parameter *./xml/schemas/myschema.xsd" is the path to the .xsd relative to program execution.
I don't want to use filenames/paths, instead I would rather compile the .xsd file as an embedded resource in my project (I have already added the .xsd file and set the Build Action to Embedded Resource).
My question is.... how do I add the Embedded Resource schema to the XmlReaderSettings schema list? There are 4 overloaded methods for settings.Schemas.Add but none of them take an embedded resource as an argument. They all take the path to the schema file.
I have used embedded resources in the past for dynamically setting label images so I am somewhat familiar with using embedded resources. Looking at my other code it looks like what I eventually end up with is a Stream that contains the content:
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
Stream myStream = myAssembly.GetManifestResourceStream(resourceName);
I am assuming that the embedded .xsd will also be read in as a stream so this narrows down my question a bit. How do I add the schema to XmlReaderSettings when I have a reference to the stream containing the schema and not the filename?
You can use the Add()
overload that takes an XmlReader
as its second parameter:
Assembly myAssembly = Assembly.GetExecutingAssembly();
using (Stream schemaStream = myAssembly.GetManifestResourceStream(resourceName)) {
using (XmlReader schemaReader = XmlReader.Create(schemaStream)) {
settings.Schemas.Add(null, schemaReader);
}
}
Or you can load the schema first and then add it:
Assembly myAssembly = Assembly.GetExecutingAssembly();
using (Stream schemaStream = myAssembly.GetManifestResourceStream(resourceName)) {
XmlSchema schema = XmlSchema.Read(schemaStream, null);
settings.Schemas.Add(schema);
}