Reputation: 193
I have a question about how to use XSD Schema to validate XML format.
I have already program successfully to validate XML format using XSD schema. However, I need to put the xx.xsd in main location of current project. Is there anyway to embed the xsd schema to the assembly so that I do not need to always put xxx.xsd to the same location of the executable assembly. I have tried to embed it to resources of the project, but it seems that I am not able to resgen a XSD file when using VS command prompt like this resgen xxx.xsd. It says the extension is not support by this command.
Are there any other ways to resolve this problems.
Any suggestions are appreciated.
Upvotes: 1
Views: 717
Reputation: 21638
If you're dealing with one XSD only (no external references), then @Romil 's answer is what you need. However, if you move to use componentized XSDs (sets of XSDs linked through xsd:include/import/redefine) then the solution is not going to work. This post on SO shows you how to correctly solve it; you need to build and use your own resolver, that's going to be able to feed these references from the embedded resources, and, also very important, that you need to provide a base URI (typically a made up URL using some proprietary scheme) when creating the first reader.
Upvotes: 3
Reputation: 20745
Step 1: Add the XSD to your class library project just as you would normally
Step 2: Right click à properties on the XSD file, and under Build Action, choose “Embedded Resource”
Step 3: Modify the code as shown here from
XmlSchemaSet schemaSet = new XmlSchemaSet() ;
schemaSet.Add("", XmlReader.Create(xmlSchema));
to
TextReader schemaStream =
new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(xmlSchema));
XmlSchemaSet schemaSet = new XmlSchemaSet() ;
schemaSet.Add("",XmlReader.Create(schemaStream));
Upvotes: 2