473,326 Members | 2,061 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

XmlValidatingReader - just the FAQS?

All,

I am having a tough time figuring out how to code a simple app to read an
xml file and an xsd file and validate the xml file using the xsd without
using a namespace for the schema. Help? Also, is there a .NET XML FAQ?

Thanks,

Will

Here are the details:

----------the error
Validation Error: The 'HeadCount' element is not declared. An error
occurred at file:///d:/xml/config.xml, (2, 2).
Validation Error: The 'Name' element is not declared. An error occurred
at file:///d:/xml/config.xml, (3, 4).
Validation Error: The 'Name' element is not declared. An error occurred
at file:///d:/xml/config.xml, (4, 4).
----------the error
----------config.xml
<?xml version="1.0" encoding="UTF-8"?>
<HeadCount>
<Name>Waldo Pepper</Name>
<Name>Red Pepper</Name>
</HeadCount>
----------config.xml
----------config.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name='HeadCount' type="HEADCOUNT"/>
<xsd:complexType name="HEADCOUNT">
<xsd:sequence>
<xsd:element name='Name' type='xsd:string' maxOccurs='unbounded'/>
</xsd:sequence>
<xsd:attribute name='division' type='xsd:int' use='optional'
default='8'/>
</xsd:complexType>
</xsd:schema>
----------config.xsd

----------doit.cs
class Tester
{
static void Main()
{
String strXml;
String strXsd;

strXml = @"d:\xml\config.xml";

strXsd = @"d:\xml\config.xsd";

Tester cs = new Tester();
cs.Validate(strXml, strXsd);
}

private void Validate(String strXml, String strXsd)
{
try
{
XmlSchemaCollection sc = new XmlSchemaCollection();
sc.ValidationEventHandler += new ValidationEventHandler
(ValidationCallBack);
sc.Add(null, strXsd);

XmlTextReader textReader = new XmlTextReader(strXml);
XmlValidatingReader validatingReader = new XmlValidatingReader
(textReader);
validatingReader.ValidationType = ValidationType.Schema;
XmlSchema schema = new XmlSchema();
schema.SourceUri = strXsd;
validatingReader.Schemas.Add(schema);
validatingReader.ValidationEventHandler += new
ValidationEventHandler(ValidationCallBack);
while (validatingReader.Read());
}
catch (System.Exception exc)
{
System.Console.Write("big bad error: \n" + exc.ToString());
}
}

private void ValidationCallBack(object sender, ValidationEventArgs e)
{
Console.WriteLine("Validation Error: {0}", e.Message);
}
}
----------doit.cs
Nov 12 '05 #1
3 2199
"Nuevo Registrado" <nu***@registrado.com> wrote in message news:Xn**********************@207.46.248.16...
read an xml file and an xsd file and validate the xml file using
the xsd without using a namespace for the schema.
The XML schema is fine, and your instance document is valid by it,
so the problem is not with these.
Validation Error: The 'HeadCount' element is not declared. An error
occurred at file:///d:/xml/config.xml, (2, 2).
Validation Error: The 'Name' element is not declared. An error occurred
at file:///d:/xml/config.xml, (3, 4).
Validation Error: The 'Name' element is not declared. An error occurred
at file:///d:/xml/config.xml, (4, 4).
Anytime I get a validation error for every possible piece of XML
in my instance document, I ask myself a question: did I really
load an XML schema, at all?

Because I have to figure that if I'm validating an instance
document against an XML schema without any declarations (i.e.,
an empty one), these are precisely the sorts of validation
errors I'd expect.
----------doit.cs
Starsky & Hutch fan?
XmlSchemaCollection sc = new XmlSchemaCollection();
sc.ValidationEventHandler += new ValidationEventHandler
(ValidationCallBack);
sc.Add(null, strXsd);
These lines _would_ work (and you're right on, passing null
to indicate that the schema targets no namespace), except
that the XmlSchemaCollection, sc, is entirely disconnected
from any of the other variables found in this method.
XmlSchema schema = new XmlSchema();
The XmlSchema constructor should only appear in applications
that are directly programming the Schema Object Model (SOM).

Whenever this line appears in an application that is just
validating an instance document against a ready-made schema,
it's got to raise a brightly colored -- if not red -- flag.
schema.SourceUri = strXsd;
It's probably a common misconception that setting SourceUri
causes a schema to be loaded; this is not actually what
happens.

The SourceUri property exists so that an XmlSchema can be
told what it's base path and resource are. As far as the
XmlSchema knows, it's been created from some nameless stream
of characters and only the application can give it a meaning-
ful context for it to use as it's Base URI. That's what the
SourceUri property is meant for.
validatingReader.Schemas.Add(schema);


Adds what I'm afraid is an absolutely empty XmlSchema to the
XmlSchemaCollection of this XmlValidatingReader. :-(

OK, there are 2 ways to resolve this. The first goes with
your winning strategy at the very top of the method, but then
instead of adding an XmlSchema to an XmlSchemaCollection that
isn't connected to anything else -- add it to the XmlSchema-
Collection on your XmlValidatingReader.

validatingReader.Schemas.Add( null, strXsd);

If you still want to access the XmlSchema object you've just
added, that's possible too, since Add() returns the newly
created XmlSchema object.

XmlSchema schema = validatingReader.Schemas.Add( null, strXsd);
schema.SourceUri = strXsd;

The second solution is to use the static Read() method of
XmlSchema. Nine times out of 10, this is always what you
want to do instead of using the XmlSchema() constructor
when you're validating an instance document against an
existing XML schema document.

XmlSchema schema = XmlSchema.Read( new XmlTextWriter( strXsd), null);
schema.SourceUri = strXsd;
validatingReader.Schemas.Add( schema);

The null argument I passed to Read() is an optional Validation-
EventHandler that allows you to receive notifications of any
warnings or errors caused while loading the XML schema document.

Either of these approaches should allow you to see that the
schema document validates your instance document without any
validation errors. :-)
Derek Harmon
Nov 12 '05 #2
Using the advice in this note, I was able to get it working. Would you
mind taking a look at my solution and telling me if it's overkill - ie.
is there a more succinct solution:

XmlSchema schema = XmlSchema.Read(new XmlTextReader(strXsd), null);
schema.SourceUri = strXsd;
XmlValidatingReader validatingReader = new XmlValidatingReader(new
XmlTextReader(strXml));
validatingReader.Schemas.Add(schema);
validatingReader.ValidationEventHandler += new ValidationEventHandler
(ValidationCallBack);
while (validatingReader.Read());

OK, and while we're on the subject why not supply a Read function like:
Read(XMLFile, XSDFile);
or
Read(XmlTextReader XmlReader, XmlTextReader XsdReader,
ValidationCallBack);

is it really that hard to anticipate the likelihood of wanting to do this
- frequently?

Derek, many thanks for your comprehensive and lucid explanation. The
reason that the schema collection was disconnected was an oversight on my
part - I had started off with one tack and finished with another - copy
and paste syndrome. I appreciate your clear answers in the face of what
might have appeared to have been air-headedness. The 'answer' was that
the schema was never 'read' and considering the weak XML related
documentation included in the MSDN library, I might never have 'figured'
it out, if it hadn't been for your kindness. Props!

Thanks,

Will
"Derek Harmon" <lo*******@msn.com> wrote in
news:OZ**************@TK2MSFTNGP09.phx.gbl:
"Nuevo Registrado" <nu***@registrado.com> wrote in message
news:Xn**********************@207.46.248.16...
read an xml file and an xsd file and validate the xml file using
the xsd without using a namespace for the schema.


The XML schema is fine, and your instance document is valid by it,
so the problem is not with these.
Validation Error: The 'HeadCount' element is not declared. An error
occurred at file:///d:/xml/config.xml, (2, 2).
Validation Error: The 'Name' element is not declared. An error
occurred at file:///d:/xml/config.xml, (3, 4).
Validation Error: The 'Name' element is not declared. An error
occurred at file:///d:/xml/config.xml, (4, 4).


Anytime I get a validation error for every possible piece of XML
in my instance document, I ask myself a question: did I really
load an XML schema, at all?

Because I have to figure that if I'm validating an instance
document against an XML schema without any declarations (i.e.,
an empty one), these are precisely the sorts of validation
errors I'd expect.
----------doit.cs


Starsky & Hutch fan?
XmlSchemaCollection sc = new XmlSchemaCollection();
sc.ValidationEventHandler += new ValidationEventHandler
(ValidationCallBack);
sc.Add(null, strXsd);


These lines _would_ work (and you're right on, passing null
to indicate that the schema targets no namespace), except
that the XmlSchemaCollection, sc, is entirely disconnected
from any of the other variables found in this method.
XmlSchema schema = new XmlSchema();


The XmlSchema constructor should only appear in applications
that are directly programming the Schema Object Model (SOM).

Whenever this line appears in an application that is just
validating an instance document against a ready-made schema,
it's got to raise a brightly colored -- if not red -- flag.
schema.SourceUri = strXsd;


It's probably a common misconception that setting SourceUri
causes a schema to be loaded; this is not actually what
happens.

The SourceUri property exists so that an XmlSchema can be
told what it's base path and resource are. As far as the
XmlSchema knows, it's been created from some nameless stream
of characters and only the application can give it a meaning-
ful context for it to use as it's Base URI. That's what the
SourceUri property is meant for.
validatingReader.Schemas.Add(schema);


Adds what I'm afraid is an absolutely empty XmlSchema to the
XmlSchemaCollection of this XmlValidatingReader. :-(

OK, there are 2 ways to resolve this. The first goes with
your winning strategy at the very top of the method, but then
instead of adding an XmlSchema to an XmlSchemaCollection that
isn't connected to anything else -- add it to the XmlSchema-
Collection on your XmlValidatingReader.

validatingReader.Schemas.Add( null, strXsd);

If you still want to access the XmlSchema object you've just
added, that's possible too, since Add() returns the newly
created XmlSchema object.

XmlSchema schema = validatingReader.Schemas.Add( null, strXsd);
schema.SourceUri = strXsd;

The second solution is to use the static Read() method of
XmlSchema. Nine times out of 10, this is always what you
want to do instead of using the XmlSchema() constructor
when you're validating an instance document against an
existing XML schema document.

XmlSchema schema = XmlSchema.Read( new XmlTextWriter( strXsd),
null); schema.SourceUri = strXsd;
validatingReader.Schemas.Add( schema);

The null argument I passed to Read() is an optional Validation-
EventHandler that allows you to receive notifications of any
warnings or errors caused while loading the XML schema document.

Either of these approaches should allow you to see that the
schema document validates your instance document without any
validation errors. :-)
Derek Harmon


Nov 12 '05 #3
"Nuevo Registrado" <nu***@registrado.com> wrote in message news:Xn***********************@207.46.248.16...
Using the advice in this note, I was able to get it working. Would you
mind taking a look at my solution and telling me if it's overkill - ie.
is there a more succinct solution:

XmlSchema schema = XmlSchema.Read(new XmlTextReader(strXsd), null);
schema.SourceUri = strXsd;
XmlValidatingReader validatingReader = new XmlValidatingReader(new
XmlTextReader(strXml));
validatingReader.Schemas.Add(schema);
validatingReader.ValidationEventHandler += new ValidationEventHandler
(ValidationCallBack);
while (validatingReader.Read());


Not overkill, but it can be shortened by one-line into,

XmlSchema schema = validatingReader.Schemas.Add( null, strXsd);
schema.SourceUri = strXsd;
XmlValidatingReader validatingReader = new XmlValidatingReader(
new XmlTextReader( strXml));
validatingReader.ValidationEventHandler += new ValidationEventHandler(
ValidationCallBack);
while (validatingReader.Read( ));

only because when you Add the file name to the XmlSchemaCollection
it will create an XmlTextReader and do the XmlSchema.Read for you.

In fact, since there is only one property on XmlSchema that's of interest
to your application, the first two lines can be compacted into:

validatingReader.Schemas.Add( null, strXsd).SourceUri = strXsd;

but that's getting a bit flamboyant for my tastes. I'd rather hold onto an
XmlSchema object reference if there's any chance I'd be interested in
more than one of it's properties in the future.
Derek Harmon
Nov 12 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: MT | last post by:
Hi, I am currently validating an XML file against a Schema using XMLValidatingReader. The schema actually contains ranges for particular elements and I have been using it to detect range errors...
0
by: Nick Finch | last post by:
Hi, I wonder if anyone else has come across this. The code below is very simple however I cannot get the ValidationHandler to be raised. I am testing with xml that I know will not validate...
4
by: Adam Smith | last post by:
XmlValidatingReader too sensitive? I have the following schemas (simplified) and xml file which validate fine in xmlspy, but blow up in xmlvalidatingreader with: 'The 'Hierarchy' element is...
4
by: Jesse Elve | last post by:
I am using an XmlValidatingReader which uses an XSD for xml validation. The code has been performing reliably for months. Yesterday it failed for the first time with the following exception: ...
9
by: jason | last post by:
how do you use the XmlValidatingReader to validate an XML document that is passed into the XmlValidatingReader constructor? it looks like the normal process is to use an underlying reader, as...
5
by: Geoff | last post by:
I am using an XMLValidatingReader to validate an XML file received via a web service. I want to verify that the incoming file matches the XML schema. When testing the validation routine, the...
1
by: Bernhard Felkel | last post by:
I have troubles validating XML files with key/keyref constraints. Here´s my schema: <?xml version="1.0" encoding="utf-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"...
1
by: Plop69 | last post by:
need some help on following: xml file 1 <TEST xmlns="http://test" > <OK>mlkddflmkj</OK> </TEST> xml file 2
12
by: Plop69 | last post by:
need some help on following: xml file 1 <TEST xmlns="http://test" > <OK>mlkddflmkj</OK> </TEST>
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.