Skip to main content

Related Articles

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

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...

The Power of ChatGPT and Whisper Models

A Deep Dive into Natural Language Processing Natural Language Processing (NLP) has seen a significant boost in recent years due to advancements in artificial intelligence and machine learning. Two models that have shown remarkable success in NLP are ChatGPT and Whisper. In this article, we will delve into the power of these models and their applications in the field of NLP. ChatGPT is a transformer-based language model developed by OpenAI that uses unsupervised learning to predict the next word in a sentence based on the context of previous words. ChatGPT is a generative model that is trained on large datasets of text, such as books and articles, and can be fine-tuned for specific tasks, such as question-answering or dialogue generation. ChatGPT is known for its ability to produce human-like text, making it an ideal tool for applications such as chatbots, content creation, and language translation. Whisper, on the other hand, is a paraphrasing model developed by Google that is based on...

DevOps automation using Python - Part 1

DevOps automation is the practice of automating the process of building, testing, and deploying software. Python is a popular language for DevOps automation because of its simplicity and versatility. In this article, we will cover the basics of getting started with DevOps automation using Python. Prerequisites Before we begin, make sure you have Python installed on your system. You can download Python from the official website at https://www.python.org/downloads/ . We will also be using some Python packages, so make sure you have the following packages installed: pip : The package installer for Python. virtualenv : A tool that creates isolated Python environments. Setting up a Virtual Environment The first step in getting started with Python DevOps automation is to set up a virtual environment. A virtual environment allows you to create a separate environment for your Python project, which can help avoid conflicts with other packages on your system. To create a virtual environment, ope...