Adding (Embedded Resource) Schema To XmlReaderSettings Instead Of Filename?

↘锁芯ラ 提交于 2019-12-01 00:27:36

问题


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?


回答1:


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);
}


来源:https://stackoverflow.com/questions/14185087/adding-embedded-resource-schema-to-xmlreadersettings-instead-of-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!