开发者

XPathNavigator.CheckValidity validates invalid XML document

I'm trying to use XPathNavigator.CheckValidity to validate an XML document. Somehow, I was able to write tests that passed using this method, but now (mysteriously) aren't passing anymore. The only thing that I can think of which changed was moving from .NET 2 to .NET 3.5, but I can't find any documentation on anything changing here during that transition.

Here's an example program:

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"" tar开发者_开发知识库getNamespace=""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>";

I've tried the solution at Validate XML with a XSD Schema without changing the XML using C#, but I'm getting the same result... I must be missing some big consideration in how this validation thing works, but I can't see it...


The problem is that your XML is using the default namespace, but the XSD specifies a target namespace. If you specify <BadManifest xmlns="http://www.engagesoftware.com/Schemas/EngageManifest"> in your XML, you should find that the validator reports errors as expected. Otherwise, since it doesn't recognise the namespace of the XML, it just ignores it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜