473,372 Members | 1,040 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,372 software developers and data experts.

XmlValidatingReader question

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;
try
{
ValidationEventHandler oVEHandler
= new ValidationEventHandler(myClass.myCallback);
oXML.ValidationEventHandler += oVEHandler;

while(oXML.Read()) {}
}
catch (Exception e)
{
// event handler creation exceptions
}

where you then create a function called myCallback to handle any actual
validation exceptions.

however, the XmlValidatingReader allows for another form of the
constructor that doesn't have an underlying XmlReader object. you can
pass in the entire XML string, as follows:
XmlParserContext oContext
= new XmlParserContext(null, null, null, XmlSpace.None);

// sInput contains an entire xml document string
XmlValidatingReader oMyVReader
= new XmlValidatingReader(sInput, XmlNodeType.Document, oContext);

but since you don't have use a Reader to acquire the XML document, how
do you perform validation on the Xml fragment?

thanks for any help,

jason

Nov 12 '05 #1
9 1908


jason wrote:

however, the XmlValidatingReader allows for another form of the
constructor that doesn't have an underlying XmlReader object. you can
pass in the entire XML string, as follows:
XmlParserContext oContext
= new XmlParserContext(null, null, null, XmlSpace.None);

// sInput contains an entire xml document string
XmlValidatingReader oMyVReader
= new XmlValidatingReader(sInput, XmlNodeType.Document, oContext);

but since you don't have use a Reader to acquire the XML document, how
do you perform validation on the Xml fragment?


The validating reader has a Read method (respectively several Read*
methods) as well so why can't you call it to pull in the nodes and
perform the validation while doing that?

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #2
well, this is being developed as a method in a Web Service, so i'm not
sure how i would build a stream to read the xml in.

it is much easier to just pass the xml in as the parameter to to Web
Service method.

and i'm guessing this is completely viable, since the ValidatingReader
has a constructor that specifically allows an XML node string as a
parameter.

can i still use the Read method even if i acquire the XML node string
through the constructor? i thought that wouldn't work, since there is
no stream that is being read from.

Nov 12 '05 #3


jason wrote:
and i'm guessing this is completely viable, since the ValidatingReader
has a constructor that specifically allows an XML node string as a
parameter.

can i still use the Read method even if i acquire the XML node string
through the constructor? i thought that wouldn't work, since there is
no stream that is being read from.


Give it a try, of course you should be able to use the Read method.
--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #4
that's actually what i was working on before i made this thread, but it
was producing unexpected results (i.e. validations were failing for
reasons that didn't make sense, such as no DTD found, and the
XmlValidatingReader unable to be set to ValidationType Schema because
of being in an invalid state) ... my hope was that these errors were
being caused by trying to use Read-time validation on a Reader that
already had the entire string passed to it in the constructor (i.e.
nothing to read)

do you happen to know a good book or online resource for showing an
example of constructor passed XML fragments being DTD and Schema
validated by an XmlValidatingReader?

thanks for the previous comments,

jason

Nov 12 '05 #5


jason wrote:

do you happen to know a good book or online resource for showing an
example of constructor passed XML fragments being DTD and Schema
validated by an XmlValidatingReader?


Here is an example I have made up now, the only special thing I had to
do is to provide a base URI to the parser context so that the relative
URI pointing to the schema could be resolved. Note that I didn't bother
to put a string literal with XML into the program but read the XML from
a file first to put it in a string then for the example:

using System;
using System.Xml;
using System.Xml.Schema;

public class Test2005042103 {
static bool valid;

public static void Main (string[] args) {
string file = args.Length > 0 ? args[0] : @"test2005042102.xml";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(file);

// from here on dealing with string only
string xmlMarkup = xmlDocument.OuterXml;

NameTable nameTable = new NameTable();
XmlNamespaceManager namespaceManager = new
XmlNamespaceManager(nameTable);
XmlParserContext parserContext = new XmlParserContext(null,
namespaceManager, null, XmlSpace.None);
parserContext.BaseURI = "file:///" + Environment.CurrentDirectory +
@"\";
XmlValidatingReader xmlValidator = new
XmlValidatingReader(xmlMarkup, XmlNodeType.Document, parserContext);
xmlValidator.ValidationEventHandler += new
ValidationEventHandler(ValidationHandler);

valid = true;
while (xmlValidator.Read()) {
Console.WriteLine("Reading node with name {0}.", xmlValidator.Name);
}
Console.WriteLine("Document is {0}.", valid ? "valid" : "not valid");
}

public static void ValidationHandler (object sender,
ValidationEventArgs args) {
Console.WriteLine("{0}: {1}", args.Severity, args.Message);
if (args.Severity == XmlSeverityType.Error) {
valid = false;
}
}

}

That example works fine for me here with .NET 1.1, the example XML
markup in the string is being pulled in node by node and validation
errors are reported.

I used an example XML

<?xml version="1.0" encoding="UTF-8"?>
<god
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="test2005042101Xsd.x ml">
<name>Kibo</name>
<power>a42</power>
</god>

with schema

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
version="1.0">

<xs:element name="god">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="power" type="xs:integer" />
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #6
thank you so much, Martin. this demonstrated a few key concepts that i
think the MSDN library was not making clear.

i do have one question though about your example. i do not see anywhere
that the Schema is being added to a Schema collection, and the
validation type of the ValidatingReader being changed to Schema? i
believe the default is simply DTD. would you be willing to show how to
add a Schema validation?

thanks again,

jason

Nov 12 '05 #7


jason wrote:

i do have one question though about your example. i do not see anywhere
that the Schema is being added to a Schema collection,
The XML document references the schema via xsi:noNamespaceSchemaLocation
so that there is no need to a add the schema explictly.
and the
validation type of the ValidatingReader being changed to Schema? i
believe the default is simply DTD.
The default is Auto and that does whatever is possible, if a DTD is
linked in via a DOCTYPE declaration it validates against the DTD, if a
schema or a schemas are present it validates against the schema(s).

would you be willing to show how to
add a Schema validation?


As said the example does schema validation by using the schema given in
the xsi:noNamespaceSchemaLocation but if you want to add the schema
manually then it looks like this

NameTable nameTable = new NameTable();
XmlNamespaceManager namespaceManager = new
XmlNamespaceManager(nameTable);
XmlParserContext parserContext = new XmlParserContext(null,
namespaceManager, null, XmlSpace.None);

XmlValidatingReader xmlValidator = new
XmlValidatingReader(xmlMarkup, XmlNodeType.Document, parserContext);

xmlValidator.ValidationEventHandler += new
ValidationEventHandler(ValidationHandler);
xmlValidator.Schemas.Add("", "test2005042101Xsd.xml");

where the first argument is "" for no namespace and where
"test2005042101Xsd.xml" is the (relative) URL where the schema is.

After that you can use the Read method as in other examples.

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #8
this all makes sense, thanks again Martin.

on last question about appropriate use of manual Schema addition: if
you didn't control the source of the XML document, and could not be
certain that it included the schema reference, would that be a good
reason to add the Schema manually, to make certain it is validated
using the schema?

my code is now reporting Schema errors with the manual schema addition.
the severity is only warning, which i find interesting, but that is
enough to confirm the validity of the doucment, and that's what i was
shooting for.

thanks again,

jason

Nov 12 '05 #9


jason wrote:

on last question about appropriate use of manual Schema addition: if
you didn't control the source of the XML document, and could not be
certain that it included the schema reference, would that be a good
reason to add the Schema manually, to make certain it is validated
using the schema?


Yes, if you want to make sure a certain schema or certain schemas are
used for validation then you have to add them yourself. This has also
the advantage that the schemas are cached so you can use the same reader
again and again without any need to reload the schemas.

--

Martin Honnen --- MVP XML
http://JavaScript.FAQTs.com/
Nov 12 '05 #10

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

Similar topics

1
by: Dmitry Martynov | last post by:
Hi I have a question whether XmlValidatingReader doesn't check keyref constrain (the same with key constraint) or I do smth wrong. I have the following schema <?xml version="1.0"...
3
by: Nuevo Registrado | last post by:
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?...
1
by: George W. | last post by:
When attempting to validate an XML file, If the file is valid, it validates correctly, and it will catch most ValidationEvents without problem. However, I keep getting the following Exception:...
3
by: jason | last post by:
i am using an XMLValidatingReader in a manner similar to the following code example: string sReturn = ""; XmlValidatingReader oXML = new XmlValidatingReader(sXMLString, XmlNodeType.Document,...
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: 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>
3
by: nshala | last post by:
Hallo, I wrote a complex XSD-Schema for validating complex XML files. By validating xs:int elements XmlValidatingReader does not validate it correctly. My XSD looks like this: .......
1
by: JoeZ | last post by:
Hi all, I have a question about using XMLValidatingReader. I have a schema files (xsd), and a xml data file. In the xml data file, if I don't specify the schema file path, XMLValidatingReader...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

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.