Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

XML Validation with XSLT & Calling Custom function from XSLT

, 2 Nov 2011
Rate this:
Please Sign up or sign in to vote.
Validating XML against defined XSL

Introduction

In this article, I will discuss about validating XML against the defined XSL. Prior to getting into this article, it’s mandatory that one should have basic knowledge on what is XML & XSL.

Consider the below XML as input (UserCheck.xml) to our application:

<?xml version="1.0" encoding="utf-16"?>
<root xmlns:func="urn:actl-xslt">
  <User>
    <UserName>suryaprakash</UserName>
    <Password>password</Password>
  </User>
</root>

This example describes the below business rules:

  1. If UserName, Password node do not exist, generate XML ERROR as output.
  2. If UserName, Password nodes are empty, generate XML ERROR as output.
  3. Check if user, password exist in DB or not & generate XML SUCCESS or ERROR as output.

The output would be as follows if there are any errors, which will be inserted into XML file (result.xml).

Each ERROR tag would represent each error with ERRORMSG & ERRORCODE.

<root xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:func="urn:actl-xslt">
  <OUTPUT>
    <ERROR>
      <ErrorMsg>
        UserName Node Contains Invalid Data
      </ErrorMsg>
      <ErrorCode>
        ERR_003
      </ErrorCode>
    </ERROR>
  </OUTPUT>
</root>

Let's get into a sample with the below steps:

  • Step 1: Define XML
  • Step 2: Define XSL as per our business rules defined above
  • Step 3: Define function which will be called from XSL
  • Step 4: Implement code validate XML with XSL as follows which will be called from XSL

Step 1: Define XML

Consider the below XML as input to our example:

<?xml version="1.0" encoding="utf-16"?>
<root xmlns:func="urn:actl-xslt">
  <User>
    <UserName>suryaprakash</UserName>
    <Password>password</Password>
  </User>
</root>

Step 2: Define XSL as per our business rules defined above

<?xml version="1.0"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt"
  xmlns:func="urn:actl-xslt">
  <xsl:template match="root">
    <root>
      <xsl:for-each select="User">
        <OUTPUT>
          <xsl:if test="not(UserName)">
            <ERROR>
              <ErrorMsg>
                UserName Node not present
              </ErrorMsg>
              <ErrorCode>
                ERR_001
              </ErrorCode>
            </ERROR>
          </xsl:if>
          <xsl:if test="not(Password)">
            <ERROR>
              <ErrorMsg>
                Password Node not present
              </ErrorMsg>
              <ErrorCode>
                ERR_002
              </ErrorCode>
            </ERROR>
          </xsl:if>
          <xsl:if test="UserName=''">
            <ERROR>
              <ErrorMsg>
                UserName Node Contains Invalid Data
              </ErrorMsg>
              <ErrorCode>
                ERR_003
              </ErrorCode>
            </ERROR>
          </xsl:if>
          <xsl:if test="Password=''">
            <ERROR>
              <ErrorMsg>
                Password Node Contains Invalid Data
              </ErrorMsg>
              <ErrorCode>
                ERR_004
              </ErrorCode>
            </ERROR>
          </xsl:if>
          <xsl:value-of select="func:checkUserExist('UserName','Password')" />
        </OUTPUT>
      </xsl:for-each>
    </root>
  </xsl:template>
</xsl:stylesheet>

For the above XSL, below are the code comments:

Code Comment #1

xmlns:func="urn:actl-xslt"

Note the attribute that I have added here as - xmlns:func="urn:actl-xslt".

Code Comment #2

The prefix added to my external method func:checkUserExist('UserName','Password') is as below:

<xsl:value-of select="func:checkUserExist('UserName','Password')" />

Code Comment #3

<xsl:if test="not(UserName)">

This tag is used to check if USERNAME node exists or not.

Code Comment #4

<xsl:if test="UserName=''"> 

This tag is used to check if content in USERNAME node is empty or not.

Step 3: Define function which will be called from XSL

This function will be called from XSL defined as <xsl:value-of select="func:checkUserExist('UserName','Password')" />.

Instead of checking username against DB, we are checking with static value. If username matches, it returns Success string else it would return ErrorStrings.

public string checkUserExist(string uName, string pWord)
    {
        string returnValue = string.Empty;
        if (uName == "prakash")
        {
            returnValue = " <SUCCESS> <SuccessMsg>
            SUCESSS </SuccessMsg><SuccessCode>SUC_000
            </SuccessCode> </SUCCESS> ";
        }
        else
        {
            returnValue = " <ERROR> <ErrorMsg>
            UserName/Password is invalid!.</ErrorMsg>
            <ErrorCode>ERR_005</ErrorCode> </ERROR> ";
        }

        return returnValue;
    }

Step 4: Implement code validate XML with XSL as follows which will be called from XSL

This below function will be called in the main method and this function declares 3 main variables for XML input, XSL input & XML output as result.xml.

public void CheckUserXslt()
{
    string sourceDoc = @"D:\Surya Prakash\WorkAround\GopalSample\XML\CheckUser.XML";
    string xsltDoc = @"D:\Surya Prakash\WorkAround\GopalSample\XML\CheckUser.xslt";
    string resultDoc = @"D:\Surya Prakash\WorkAround\GopalSample\XML\result.xml";
    XsltArgumentList xsltArguments = null;
    XsltExtension xsltExtension = new XsltExtension();
    xsltArguments = new XsltArgumentList();
    xsltArguments.AddExtensionObject("urn:actl-xslt", xsltExtension);

    XPathDocument myXPathDocument = new XPathDocument(sourceDoc);
    XslTransform myXslTransform = new XslTransform();
    XmlTextWriter writer = new XmlTextWriter(resultDoc, null);
    myXslTransform.Load(xsltDoc);
    myXslTransform.Transform(myXPathDocument, xsltArguments, writer);
    writer.Close();
    StreamReader stream = new StreamReader(resultDoc);
}

Finally, run the application by modifying the input XML & see the output in result.xml.

Happy coding… hope this helps!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Bangla Gopal Surya Prakash
Software Developer (Senior)
United States United States
B.Tech graduate in CSE, having experience in .Net related Technologies
 
Microsoft Certified Technical Specialist in .NET Framework 2.0
Microsoft Certified Technical Specialist in .NET Framework 4.0
 
My interests are Coding, reading [technical stuff] and listening to music, playing Cricket, Table Tennis
 
http://bgsuryablog.blogspot.com/

Comments and Discussions

 
QuestionXsltExtension not present PinmemberSusanta5783-Nov-11 2:48 
AnswerRe: XsltExtension not present [modified] PinmemberBangla Gopal Surya3-Nov-11 19:10 
GeneralRe: XsltExtension not present PinmemberSusanta5783-Nov-11 19:47 
GeneralRe: XsltExtension not present PinmemberSusanta5783-Nov-11 20:01 
I made it work. Thanks.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140916.1 | Last Updated 2 Nov 2011
Article Copyright 2011 by Bangla Gopal Surya Prakash
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid