2010-12-03 130 views
1

我试图使用XPathNavigator.CheckValidity验证XML文档。不知何故,我能够编写通过此方法传递的测试,但现在(神秘地)不再传递。我能想到的唯一变化就是从.NET 2转移到.NET 3.5,但在转换过程中我找不到任何有关更改的文档。XPathNavigator.CheckValidity验证无效的XML文档

下面是一个例子程序:

void Main() 
{ 
    try 
    { 
     GetManifest().CreateNavigator().CheckValidity(GetSchemaSet(), (sender, args) => { 
      // never get in here when debugging 
      if (args.Severity == XmlSeverityType.Error) { 
       throw new XmlSchemaValidationException("Manifest failed validation", args.Exception); 
      } 
     }); // returns true when debugging 
    } 
    catch (XmlSchemaValidationException) 
    { 
     // never get here 
     throw; 
    } 

    // code here runs 
} 

IXPathNavigable GetManifest() 
{ 
    using (TextReader manifestReader = new StringReader("<?xml version='1.0' encoding='utf-8' ?><BadManifest><bad>b</bad></BadManifest>")) 
    { 
     return new XPathDocument(manifestReader); 
    } 
} 

XmlSchemaSet GetSchemaSet() 
{ 
    var schemaSet = new XmlSchemaSet(); 
    using (var schemaReader = new StringReader(Schema)){ 
     schemaSet.Add(XmlSchema.Read(schemaReader, null)); 
    } 

    return schemaSet; 
} 

const string Schema = @"<?xml version=""1.0"" encoding=""utf-8"" ?> 
<xs:schema attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" targetNamespace=""http://www.engagesoftware.com/Schemas/EngageManifest""> 
    <xs:element name=""EngageManifest""> 
    <xs:complexType> 
     <xs:all> 
     <xs:element name=""Title"" type=""xs:string"" /> 
     <xs:element name=""Description"" type=""xs:string"" /> 
     </xs:all> 
    </xs:complexType> 
    </xs:element> 
</xs:schema>"; 

我试过在Validate XML with a XSD Schema without changing the XML using C#的解决方案,但我得到了同样的结果。我必须失去了在这个验证的事情是如何工作的一些大的方面考虑,但我看不到它...

回答

3

问题是您的XML使用默认名称空间,但XSD指定了目标名称空间。如果您在XML中指定了<BadManifest xmlns="http://www.engagesoftware.com/Schemas/EngageManifest">,则应该发现验证器按预期报告错误。否则,由于它不能识别XML的名称空间,因此它会忽略它。

+0

那么,有没有一种方法可以在不需要文档中的xmlns的情况下对模式进行验证?如果没有带有指定targetNamespace的XSD的xmlns,是不可能验证文档的? – bdukes 2010-12-06 18:38:11