Caveman's Blog

My commitment to learning.

Posts Tagged ‘XML

Sample Code: Xml validation using XSD

leave a comment »

In this blog I will post a handy code snippet, that validates an XML file using an XSD file.

Import the following namespaces

using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;

Validate a XML File

public static void ValidateXmlFile(string XMLfilename, string XSDfilename)
    //make sure the file exists
    if (!File.Exists(XMLfilename))
        Console.WriteLine("Error: XML Data File '{0}' not found.", XMLfilename);
        return 0;

    //Standard schema validation first
    XmlDocument document = new XmlDocument();
    catch (XmlException xmle)
        Console.WriteLine("!!!Error!!!\r\nXML Validation Failure: {0}\r\n\r\n", xmle.Message);
        return 0;
    document.Schemas.Add(XSDfilename, "");
    ValidationEventHandler validation = new ValidationEventHandler(SchemaValidationHandler);

Define a Schema Validation Handler

private static void SchemaValidationHandler(object sender, ValidationEventArgs e)
     switch (e.Severity)
         case XmlSeverityType.Error:
             Console.WriteLine("Schema Validation Error: {0}", e.Message);
         case XmlSeverityType.Warning:
             Console.WriteLine("Schema Validation Warning: {0}", e.Message);
    return 0;

Written by cavemansblog

July 6, 2012 at 11:17 am

Replace special characters in XML, using C#

leave a comment »

We can use the SecurityElement.Escape method to replace the invalid XML characters in a string with their valid XML equivalent [1]. The following table shows the invalid XML characters and their respective replacements.

invalid XML Character

Replaced With











srtXML = SecurityElement.Escape(strXML);

Namespace: System.Security
Assembly: mscorlib (in mscorlib.dll)

I have used the HttpUtility classes UrlEncode and UrlDecode methods to handle cross-site scripting attacks and this also helped me to get rid of the XmlException – “Data at the root level is invalid”.


Written by cavemansblog

March 25, 2008 at 8:57 pm