473,795 Members | 2,968 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

XmlValidatingRe ader - 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:complexTyp e name="HEADCOUNT ">
<xsd:sequence >
<xsd:element name='Name' type='xsd:strin g' maxOccurs='unbo unded'/>
</xsd:sequence>
<xsd:attribut e 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(str Xml, strXsd);
}

private void Validate(String strXml, String strXsd)
{
try
{
XmlSchemaCollec tion sc = new XmlSchemaCollec tion();
sc.ValidationEv entHandler += new ValidationEvent Handler
(ValidationCall Back);
sc.Add(null, strXsd);

XmlTextReader textReader = new XmlTextReader(s trXml);
XmlValidatingRe ader validatingReade r = new XmlValidatingRe ader
(textReader);
validatingReade r.ValidationTyp e = ValidationType. Schema;
XmlSchema schema = new XmlSchema();
schema.SourceUr i = strXsd;
validatingReade r.Schemas.Add(s chema);
validatingReade r.ValidationEve ntHandler += new
ValidationEvent Handler(Validat ionCallBack);
while (validatingRead er.Read());
}
catch (System.Excepti on exc)
{
System.Console. Write("big bad error: \n" + exc.ToString()) ;
}
}

private void ValidationCallB ack(object sender, ValidationEvent Args e)
{
Console.WriteLi ne("Validation Error: {0}", e.Message);
}
}
----------doit.cs
Nov 12 '05 #1
3 2231
"Nuevo Registrado" <nu***@registra do.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?
XmlSchemaCollec tion sc = new XmlSchemaCollec tion();
sc.ValidationEv entHandler += new ValidationEvent Handler
(ValidationCall Back);
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 XmlSchemaCollec tion, 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.SourceUr i = 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.
validatingReade r.Schemas.Add(s chema);


Adds what I'm afraid is an absolutely empty XmlSchema to the
XmlSchemaCollec tion of this XmlValidatingRe ader. :-(

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 XmlSchemaCollec tion that
isn't connected to anything else -- add it to the XmlSchema-
Collection on your XmlValidatingRe ader.

validatingReade r.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 = validatingReade r.Schemas.Add( null, strXsd);
schema.SourceUr i = 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.SourceUr i = strXsd;
validatingReade r.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(s trXsd), null);
schema.SourceUr i = strXsd;
XmlValidatingRe ader validatingReade r = new XmlValidatingRe ader(new
XmlTextReader(s trXml));
validatingReade r.Schemas.Add(s chema);
validatingReade r.ValidationEve ntHandler += new ValidationEvent Handler
(ValidationCall Back);
while (validatingRead er.Read());

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

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******** ******@TK2MSFTN GP09.phx.gbl:
"Nuevo Registrado" <nu***@registra do.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?
XmlSchemaCollec tion sc = new XmlSchemaCollec tion();
sc.ValidationEv entHandler += new ValidationEvent Handler
(ValidationCall Back);
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 XmlSchemaCollec tion, 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.SourceUr i = 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.
validatingReade r.Schemas.Add(s chema);


Adds what I'm afraid is an absolutely empty XmlSchema to the
XmlSchemaCollec tion of this XmlValidatingRe ader. :-(

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 XmlSchemaCollec tion that
isn't connected to anything else -- add it to the XmlSchema-
Collection on your XmlValidatingRe ader.

validatingReade r.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 = validatingReade r.Schemas.Add( null, strXsd);
schema.SourceUr i = 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.SourceUr i = strXsd;
validatingReade r.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***@registra do.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(s trXsd), null);
schema.SourceUr i = strXsd;
XmlValidatingRe ader validatingReade r = new XmlValidatingRe ader(new
XmlTextReader(s trXml));
validatingReade r.Schemas.Add(s chema);
validatingReade r.ValidationEve ntHandler += new ValidationEvent Handler
(ValidationCall Back);
while (validatingRead er.Read());


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

XmlSchema schema = validatingReade r.Schemas.Add( null, strXsd);
schema.SourceUr i = strXsd;
XmlValidatingRe ader validatingReade r = new XmlValidatingRe ader(
new XmlTextReader( strXml));
validatingReade r.ValidationEve ntHandler += new ValidationEvent Handler(
ValidationCallB ack);
while (validatingRead er.Read( ));

only because when you Add the file name to the XmlSchemaCollec tion
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:

validatingReade r.Schemas.Add( null, strXsd).SourceU ri = 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
1851
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 before it gets to my program. The way the rangechecking works is that every element that needs range checking is defined as an element with a particular type in the XSD. For example, <xs:element name="Row" maxOccurs="48">
0
1880
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 against the XmlSchema that I have added to the Schemas collection of the XmlValidatingReader. I also know that the schema is sound, if I comment out the delegate assignment and wrap the code in a try/catch then I get the exception that I expect.
4
1620
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 not declared. An error occurred'. Any help appreciated. To give a brief explanation of what I'm trying to do, the schema 1 is a
4
2606
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: Inner exception of type System.InvalidOperationException has occurred : The operation is not valid due to the current state of the object. [stack trace = at System.Xml.XmlValidatingReader.set_ValidationType(ValidationType
9
1942
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 follows (C#): XmlValidatingReader oMyVReader = new XmlValidatingReader(oMyReader); oMyVReader.Schemas.Add(oMySchemaCollection); oMyVReader.ValidationType = ValidationType.Schema;
5
1414
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 XMLValidatingReader correctly flags mis-matched tags such as <abc>some content</xyz> but does not catch other errors. For example, it doesn't catch tags that are not part of the schema, doesn't catch missing tags where the schema has minoccurs="1", and...
1
2114
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" xmlns:transNS="http://Festo.Common.Translation" xmlns="http://Festo.Common.Translation" targetNamespace="http://Festo.Common.Translation" elementFormDefault="qualified" attributeFormDefault="unqualified" version="1.0.1">
1
1848
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
8569
by: Plop69 | last post by:
need some help on following: xml file 1 <TEST xmlns="http://test" > <OK>mlkddflmkj</OK> </TEST>
1
10165
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9043
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7541
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6783
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5437
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3727
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.