問題描述
我正在編寫一個解析 Xml 文件的應用程序.我有架構 (.xsd) 文件,用于在嘗試反序列化之前驗證 Xml:
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);
請注意,參數 *./xml/schemas/myschema.xsd" 是 .xsd 相對于程序執行的路徑.
Note that the parameter *./xml/schemas/myschema.xsd" is the path to the .xsd relative to program execution.
我不想使用文件名/路徑,而是將 .xsd 文件編譯為我的項目中的嵌入式資源(我已經添加了 .xsd 文件并將構建操作設置為嵌入式資源).
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).
我的問題是....如何將嵌入式資源架構添加到 XmlReaderSettings 架構列表?settings.Schemas.Add 有 4 個重載方法,但沒有一個將嵌入資源作為參數.它們都采用架構文件的路徑.
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.
我過去使用嵌入式資源來動態設置標簽圖像,因此我對使用嵌入式資源有些熟悉.查看我的其他代碼,看起來我最終得到的是一個包含內容的 Stream:
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);
我假設嵌入的 .xsd 也將作為流讀入,所以這稍微縮小了我的問題.當我引用包含架構而不是文件名的流時,如何將架構添加到 XmlReaderSettings?
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?
推薦答案
您可以使用 Add()
重載,該重載將 XmlReader
作為其第二個參數:
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);
}
這篇關于將(嵌入式資源)架構添加到 XmlReaderSettings 而不是文件名?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!