【问题标题】:How to validate an XML file with a schema in memory with .NET?如何使用 .NET 在内存中使用架构验证 XML 文件?
【发布时间】:2010-12-08 08:11:29
【问题描述】:

是否可以使用在运行时从嵌入式应用程序资源加载的 XSD 验证 XML 文件,而不是使用物理文件,使用 .NET(框架 3.5)?

提前致谢

【问题讨论】:

    标签: .net xsd


    【解决方案1】:

    你可以使用XmlSchemaCollection.Add(string, XmlReader):

    string file = "Assembly.Namespace.FileName.ext";
    XmlSchemaCollection xsc = new XmlSchemaCollection();
    xsc.Add(null, new XmlTextReader(
        this.GetType().Assembly.GetManifestResourceStream(file)));
    

    【讨论】:

    • 谢谢,我想出了如何实现“......你的资源流在这里......”现在它可以工作了
    • 我该如何改进这个答案,马可?
    • 我觉得还可以,但也许你可以描述或添加一个链接如何从程序集中检索嵌入的资源文件
    【解决方案2】:

    这是我的:

    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 验证不是我完全在意...

    【讨论】:

      【解决方案3】:

      看看它是如何在 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));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-04
        • 2013-03-15
        • 2010-09-08
        • 2014-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多