【发布时间】:2010-12-08 08:11:29
【问题描述】:
是否可以使用在运行时从嵌入式应用程序资源加载的 XSD 验证 XML 文件,而不是使用物理文件,使用 .NET(框架 3.5)?
提前致谢
【问题讨论】:
是否可以使用在运行时从嵌入式应用程序资源加载的 XSD 验证 XML 文件,而不是使用物理文件,使用 .NET(框架 3.5)?
提前致谢
【问题讨论】:
你可以使用XmlSchemaCollection.Add(string, XmlReader):
string file = "Assembly.Namespace.FileName.ext";
XmlSchemaCollection xsc = new XmlSchemaCollection();
xsc.Add(null, new XmlTextReader(
this.GetType().Assembly.GetManifestResourceStream(file)));
【讨论】:
这是我的:
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;
}
您可以通过以下方式使用它:
var xe = XElement.Parse(myXmlString); //by memory; may be wrong
var result = IsValid(xe, MyApp.Properties.Resources.MyEmbeddedXSD);
这并不能保证这是 100%;这对您来说只是一个很好的起点。 XSD 验证不是我完全在意...
【讨论】:
看看它是如何在 Winter4NET 中完成的。完整源代码is here。基本代码摘录:
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));
【讨论】: