views:

609

answers:

4

Hi All

I'm having some issues validating some XML against a Schema, using .net and C#.

I am using XmlReaderSettings with the ValidationEventHandler.

However, this seems to stop catching errors after it has encountered the first error at a particular level within the XML file, instead of checking the next tag at the same level, so basically it does not check each and every tag within the XML file instead skipping a level when it has found an error.

I was hoping to get some advice from somebody who has successfully accomplished this type of validation.

Thanks very much

A: 

How are you handling the ValidationEvent?

Could we see some code?

Malfist
A: 

Is the issue that the XML is not valid per the schema or that it is just not valid XML at all?

bradmurray
A: 

The XMLReader is described as a

reader that provides fast, non-cached, forward-only access to XML data.

from the API documentation and from your descriptions of the behavior of your application it sounds like an exception is thrown and that there is defined some form of validation callback method that does something non-fatal (like logging a warning) and then returns control to the validator one level above the offending element.

By the way: xml elements are called 'elements', not 'tags'

Steen
A: 

This sounds like you have a xsd:sequence defined in your schema and the error occurs when the order of elements in your document does not match the order of the elements defined in the schema.

Given this schema:

<?xml version="1.0" encoding="utf-8"?>
<xsd:schema 
    attributeFormDefault="unqualified" 
    elementFormDefault="qualified" 
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
    <xsd:element name="Dog">
     <xsd:complexType>
      <xsd:sequence>
       <xsd:element name="Age" type="xsd:int"/>
       <xsd:element name="Name" type="xsd:string"/>
      </xsd:sequence>
     </xsd:complexType>
    </xsd:element>
</xsd:schema>

and this XML:

<Dog>
    <Name>Rex</Name>
    <Age>three</Age>
</Dog>

You would imagine that validation would create two errors:

1. The element 'Dog' has invalid child element 'Name'.
2. The 'Age' element is invalid - The value 'three' is invalid according to its datatype

But you only see the first error. This is because the first error of invalid child element makes it impossible for the XmlReader to parse the remainder of the document as it no longer knows what to expect next.

Andrew Hare