使用xsd:any的模式 - XmlReader验证错误

时间:2009-08-16 00:05:22

标签: c# .net xsd xmlreader

尝试使用xsd:any元素时,我的架构中的类型有问题 在验证期间,我有验证异常:未声明'MerchantAccount'元素。

我们的想法是能够在ExtendedProperties元素中指定任何属性和值。 请告诉我我做错了什么。

架构的一部分

...
<xsd:complexType name="ExtendedPropertiesType">
    <xsd:sequence>
      <xsd:any minOccurs="0" maxOccurs="unbounded" />
    </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="ProcessorInstanceType">
  <xsd:all>
    <xsd:element name="Id" type="xsd:string" />
    <xsd:element name="Descriptor" type="xsd:string" />
    <xsd:element minOccurs="0" name="ExtendedProperties" type="ExtendedPropertiesType" />
  </xsd:all>
  <xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
...

xml文件的一部分:

...
<ProcessorInstance name="aaaa">
  <Id>37fc527b-2845-43d0-99ca-ac1ff6f0ed86</Id>
  <Descriptor>Test</Descriptor>

  <ExtendedProperties>
    <MerchantAccount>1111</MerchantAccount>
  </ExtendedProperties>
</ProcessorInstance>
...

验证码:

private static XmlDocument loadConfigurationXml(FileInfo configFile)
    {
        //load schema
        var sr = new StringReader(Schemas.ConfigurationSchema);
        var schema = XmlSchema.Read(sr, (o, ea) => { throw ea.Exception; });
        //validate against the schema
        var schemas = new XmlSchemaSet();
        schemas.Add(schema);
        var readerSettings = new XmlReaderSettings
        {
            ValidationType = ValidationType.Schema, 
            ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings,
            Schemas = schemas,
        };
        readerSettings.ValidationEventHandler += (o, ea)=>
        {
            throw new PaynetValidationException(
                string.Format("Invalid configuration file, see schema for details: {0}", 
                              ea.Message), 
                ea.Exception);
        };
        var reader = XmlReader.Create(configFile.FullName, readerSettings);
        //parse and validate config file
        while (reader.Read()){}

        var ret = new XmlDocument();
        if (configFile.Length != 0)
            ret.Load(configFile.FullName);

        return ret;
    }

1 个答案:

答案 0 :(得分:4)

这是因为processContents属性的默认值为strict。如果您希望在没有元素架构时进行验证,请使用

<xs:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/>
顺便说一句,如果您正在设计此架构,我建议您远离xs:all。允许以任何顺序输入元素可能听起来是个好主意,但这可能会导致模糊的内容模型,并且可以驱动处理模式的代码绝对疯狂。