Skip to main content

How To Validate XML Document With ASP.NET

In my previous article, we discussed on how to generate XML document or XML stream from your dataset. There I mentioned that one of the major advantage of converting a dataset into XML is we can easily validate our XML data against the XML schema. The XML schema is used to define the format, data types and key constraints that you want to validate. The XML document or XML stream can be validate against the predefined XML schema and exactly you can get the validation error and on which tag that error is occurred.

First you need to have a XML document to validate. There are several ways to convert your data into XML documents. In previous article I showed you one such method. In this article I will show you how to do a validation with XML schema for existing XML document.



Step 1:

Define you XML schema that you need to validate your data with it. In Microsoft Visual Studio 2005 it very easy to define your XML schema since they have provided a graphical tool. First add XML schema file to your project solution. Please note that both XML Schema and Dataset file extensions ".xsd" since they have used common technologies. But here you should only add XML schema file not Dataset file.


Fig 1: Add XML Schema File to Solution
Using XML Schema Toolbox you can define element, attribute, attributeGroup, complexType, simpleType, group, facet, key and relationship in you schema.
Fig 2: XML Schema Toolbox
Fig 3: Sample XML Schema
Once you draw your XML schema here it will automatically generate XML code for the schema.
Step 2:
Next step is to load your XML file and validate it against the schema defined above. You need to load both XML document and XML schema into memory stream. Add resolver to pass security if accessing web site to receive schema. Last step is validation of XML document. You need use to following namespace in you coding.
using System.IO;
using System.Xml;
using System.Xml.Schema;
FileStream is used load XML file and define XmlDocument called "xdoc". XmlReaderSettings object is used to set XML Schema, XMLResolver and ValidationType. Load() method is used to load XML document and Validate() method is used to validate the XML document.
//load instance into memory
FileStream fs = File.Open("../../XMLFile1.xml", FileMode.Open);
XmlDocument xdoc = new XmlDocument();
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, "../../XMLSchema1.xsd");

//add resolver to pass security if accessing web site to receive schema
XmlUrlResolver resolver = new XmlUrlResolver();
resolver.Credentials = System.Net.CredentialCache.DefaultCredentials;
settings.XmlResolver = resolver;
//this line is necessary for validation to work
settings.ValidationType = ValidationType.Schema;
ValidationEventHandler veh = new ValidationEventHandler(xvr_ValidationEventHandler);
settings.ValidationEventHandler += veh;
XmlReader reader = XmlReader.Create(fs, settings);
xdoc.Load(reader);
xdoc.Validate(veh);
ValidateEventHandler is used to define what action to take if the XML document is invalid. In this example I have written separate method called "xvr_ValidationEventHandler" to fire when the xml schema is not valid. Inside this method you write what actually you want to do if XML file is not valid according to the XML schema.
private void xvr_ValidationEventHandler(object sender, ValidationEventArgs args)
{
// The xml does not match the schema.
this.richTextBox1.Text = args.Exception.InnerException.ToString();
}
In this example I have written the Exception message into rich text box once the XML document is invalid.

Try and see how easy to work with XML language.

Comments

Popular posts from this blog

PrimeNG UI Components For Angular Application

Getting Started With PrimeNG Styling in Angular App  This chapter we are going to check how you can add PrimeNG card component to show available flowers in the stock. Before styling the app, I have added some images of flowers to our assets folder as below. In app.module.ts file you can import PrimeNG Card module as below. import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { LandingComponent } from './modules/landing/landing.component'; import { HomeComponent } from './modules/home/home.component'; import { CardModule } from 'primeng/card'; ; @NgModule({   declarations: [     AppComponent,     LandingComponent,     HomeComponent   ],   imports: [     BrowserModule,     AppRoutingModule,     CardModule,        ],   provider...

Building robust APIs with Node.js

Node.js is a popular open-source JavaScript runtime environment that allows developers to build scalable and high-performance web applications. One of the key strengths of Node.js is its ability to build APIs quickly and efficiently. APIs, or Application Programming Interfaces, allow different systems to communicate with each other, enabling data exchange and other operations. Building robust APIs with Node.js requires an understanding of RESTful architecture, which is a widely adopted standard for creating APIs. RESTful APIs provide a standardized way to expose data and functionality over the web using a set of HTTP methods such as GET, POST, PUT, and DELETE. To build a robust Node.js API, developers must choose an appropriate framework and set up a development environment. They should also handle errors and exceptions, implement authentication and authorization, and use middleware to enhance the functionality of the API. Writing test cases, documenting the API using tools such as Swa...

SMPP protocol library for fast and easy SMSC(Short Message Service Centre) client development even for non-telecom guys

SMS sending through .NET C# is really easy. But most of the guys face many issues with SMSC client developments. SMPP protocol has many parameters to configure, but for simple SMPP gateway application you need very few of them to configure correctly. This article will cover how to implement SMSC client application using EasySMPP library. EasySMPP is a free SMPP library used by many people to implement SMS sending applications. There are many SMPP libraries but EasySMPP library is very easy to use and relatively stable. EasySMPP library mainly contain five class library projects. KernelParameters, SMPPClient, SMSClient, SMSService and Tools are the library projects and you only need to use SMSClient library to implement SMPP client application. First download EasySMPP library and add class library project to your .NET C# solution.  1. public bool SendSms( string from, string to, string text)