473,785 Members | 2,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Howto: Validate in memory XML against in memory Schema

Hi
I have two strings in memory, a XML document and a Schema, I would like a
function that takes these two as parameters and returns an errordescriptio n
if the XML does not validate and an empty stirng if the XML does validate
againsg the schema.

What's the easiest way to do this?

Kind Regards,
Allan Ebdrup
Nov 17 '05 #1
2 3809
Allan Ebdrup wrote:
Hi
I have two strings in memory, a XML document and a Schema, I would like a
function that takes these two as parameters and returns an errordescriptio n
if the XML does not validate and an empty stirng if the XML does validate
againsg the schema.

What's the easiest way to do this?


Use an XmlValidatingRe ader.

example:
/// <summary>
/// TemplateSetConf igValidator.
/// </summary>
public class TemplateSetConf igValidator
{
#region Class Member Declarations
private string _contentsToVali date;
private ArrayList _errors;
private XmlValidatingRe ader _validator;
private XmlSchemaCollec tion _xsdCollection;
#endregion
/// <summary>
/// CTor
/// </summary>
public TemplateSetConf igValidator(str ing contentsToValid ate)
{
_contentsToVali date = contentsToValid ate;
_errors = new ArrayList();
_xsdCollection = new XmlSchemaCollec tion();

_xsdCollection. Add("http://sd/llblgen/pro/templateSetConf igDefinition.xs d",
Path.Combine(Ap plication.Start upPath,
Constants.Templ ateSetConfigXsd Filename));
}
/// <summary>
/// Validates the set contents if it contains errors. Returns an
arraylist with error informatoin
/// </summary>
/// <returns>true if there are no errors, otherwise false;</returns>
public bool Validate()
{
_errors.Clear() ;

try
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhi tespace=true;
doc.LoadXml(_co ntentsToValidat e);

// try to find <templateSetDef inition> node
XmlNode root = doc.SelectSingl eNode("/templateSetDefi nition");
if(root==null)
{
// not found.
throw new Exception("temp lateSetDefiniti on node not found");
}

XmlAttribute nsAttribute = null;
if(doc.Attribut es!=null)
{
nsAttribute = (XmlAttribute)d oc.Attributes.G etNamedItem("xm lns");
}
if(nsAttribute= =null)
{
nsAttribute = doc.CreateAttri bute("xmlns");
root.Attributes .Append(nsAttri bute);
}
nsAttribute.Val ue = Constants.Templ ateSetConfigTar getNamespace;

_validator = new XmlValidatingRe ader(doc.OuterX ml,
XmlNodeType.Ele ment, null);
_validator.Sche mas.Add(_xsdCol lection);

_validator.Vali dationType = ValidationType. Schema;
_validator.Vali dationEventHand ler+=new
ValidationEvent Handler(validat or_ValidationEv entHandler);

while(_validato r.Read())
{
// optional element examination here;
// The ValidationEvent event is raised whenever an error is encountered
}
}
catch(Exception ex)
{
_errors.Add(new XmlValidationEx ception(ex.Mess age, 1, 1));
}

return (_errors.Count= =0);
}
private void validator_Valid ationEventHandl er(object sender,
ValidationEvent Args e)
{
_errors.Add(new XmlValidationEx ception(e.Excep tion.Message,
e.Exception.Lin eNumber, e.Exception.Lin ePosition));
}

....

Frans

--
------------------------------------------------------------------------
Get LLBLGen Pro, productive O/R mapping for .NET: http://www.llblgen.com
My .NET blog: http://weblogs.asp.net/fbouma
Microsoft MVP (C#)
------------------------------------------------------------------------
Nov 17 '05 #2
"Frans Bouma [C# MVP]" <pe************ ******@xs4all.n l> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
Use an XmlValidatingRe ader.

[Cut - Code]

Doesn't your code read the XSD from a file?
I should remove all the stuff with <templateSetDef inition> right?

Kind Regards,
Allan Ebdrup
Nov 17 '05 #3

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

Similar topics

9
12476
by: Leona | last post by:
Hello all, does anyone know of a tool, preferably free, preferably on linux, which will take an xml file and validate it against your own custom W3C XML Schema file (.xsd) ?? All help appreciated - it's proving very difficult to find. Failing that, does anyone know how to get the W3C's own online validating engine (XSV, I think it's called) to do the same job? I can't get it to do what I want and I can't really understand the output.
1
1755
by: QuantDev | last post by:
Hi NG, I would need to validate an XML fragment against a type defined within an XSD (which defines many other things). What is the correct way of achieving this? QD2004
1
1328
by: Randy | last post by:
I have a class which inherits from XmlDocument. Inside it has a public method which builds the xml after properties have been set. My question is how would I make this class validate itself against a schema? One of the documents attributes is xmlns:schemaLocation=http://www.irs.gov/efile C:\Schema.xsd"
1
1447
by: Ron Rohrssen | last post by:
I've been working on learning XML schemas and trying to make use of the MS classes for validating data against a schema. So, I've been trying to work through some simple schemas and instances. But, the parser inside of Visual Studio seems to frequently validate against a cached version of the schema. Occassionally I have an XML file that won't validate
1
9109
by: aevans1108 | last post by:
Greetings All If this is the wrong place to post this question, please give me a push in the right direction. Thanks. I know there has to be a simpler way to do this, but this is as simple a way as I could come up with. Yes, it's obvious I don't know what I'm doing. I'm creating an XSD string and an XML string at runtime (ie: NOT read
6
4434
by: LesleyW | last post by:
Hi Apologies if this is a really dumb question, but being new to XML and Schemas, I wonder if giving the namespace for eg xsd or xsi as a website address means that the user has to be online when they run the app? If so, what should I do if I can't guarantee that they will be? Can I bring all these files into the app? Is that desirable? I'm about to write an app that takes an XML file as input, using Visual Studio 2005 Express and SQL...
7
16279
by: Ali-R | last post by:
Hi all, I am getting a CSV file like this from our client: "C1","2","12344","Mr","John","Chan","05/07/1976"......... I need to validate **each filed value** against a set of rules ,for instance for "05/07/1976" ,I need to make sure that it's in the right format ,It's not later than today and lots of other rules ,Is there somebody who can help me how to that?Can I map it to some sort of xml schema or something?
6
5935
by: Ian Boyd | last post by:
Every time during development we had to make table changes, we use Control Center. Most of the time, Control Center fails. If you try to "undo all", it doesn't, and you end up losing your identity seed, or your constraints, or your triggers, or your table. Talking to developers at other companies who have had the misfortune of using DB2, they are adamant that you cannot use the tools; they are buggy and you just have to resign yourself to...
1
1594
by: JoeZ | last post by:
Hi all, I am using XMLValidatingReader to validate an xml instance against the xml schema. Currently the schema has the targetnamespace, but the instance doesn't have a namespace. Can I still use XMLValidatingReader to do the validation, without modifying either the schema or the instance? This is .NET framework 1.1.
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10324
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10090
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
8971
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
7499
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
6739
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2879
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.