Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

XDocument.Validate fails to reject invalid document?

29 views
Skip to first unread message

Bill Cohagan

unread,
Jan 6, 2010, 11:30:01 AM1/6/10
to
I'm using LINQ to XML and trying to validate an XDocument object against an
XSD. I have a (NUnit) test that intends to demo the validator rejecting an
invalid document; however it appears to accept it without complaint!. I'm
using VS2010B2 (but targetting Framework 3.5)

The XSD file is an embedded resource and I'm using a custom resolver to
provide the necessary stream object for included schemas. Using breakpoints
I've verified that it's picking up the correct schemas. I create the "root"
XmlSchema, add it to a schemas collection, compile the collection, then call
the Validate method on the XDocument object, passing in the schema
collection, and error handler. The handler is never called.

For the test I'm passing in:

new XDocument(new XElement("foo"))

which isn't even the right namespace (as defined in the XSD) -- nor is
element named foo defined in the XSD.

At this point I'm stumped. Any suggestions or pointers would be greatly
appreciated.

Thanks in advance,
Bill

Martin Honnen

unread,
Jan 6, 2010, 12:55:03 PM1/6/10
to
Bill Cohagan wrote:

> For the test I'm passing in:
>
> new XDocument(new XElement("foo"))
>
> which isn't even the right namespace (as defined in the XSD) -- nor is
> element named foo defined in the XSD.

That is the problem, the validator looks for a schema with the
targetNamespace of the element to validate and if it does not find one
it does lax validation.
If you use XmlReader for validation you can use XmlReaderSettings with
warnings enabled and you will get a warning emitted to your validation
event handler.
Unfortunately, as far as I aware, the LINQ to XML validation does not
allow that so you will always need to add your own code that compares
the namespace of the XML input document to the targetNamespace(s) of
your schema(s) if you expect to receive XML documents with namespaces
for which you do not have a schema.

For your first test I would suggest to create an element in the
targetNamespace of the schema for which no definition exists, then, if
all is set up correctly, I am sure you will get a validation error:
XNamespace ns = "http://example.com/foo";// put targetNamespace here
XDocument doc = new XDocument(new XElement(ns + "foo"));

--

Martin Honnen --- MVP XML
http://msmvps.com/blogs/martin_honnen/

0 new messages