How to use regular expression validation for value at user defined XPAth in XML file?
If you want to check value at a particular XPath matches with regular expression provided by you , then you can use following code snippet. Code has been developed in C#. You can place this code in any .cs file and use the same.
Introduction
User has to give input as XPath, regular expression and XML file which he wants to use for this match checking purpose.
Instead of using several methods for alphanumeric ,numeric , date checking regular expressions , user has to customize all in one single method.
Suppose your XML file is test1.xml and XPath in test1.xml is //students/student/First-name then user has to also specify which type of regular expression he wants to check against this mentioned XPath.
Lets say , user wants to apply alphanumeric regular expression then , he has to send input ^[a-zA-Z0-9]*$ for the parameter used for regular expression.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Text.RegularExpressions;
namespace yourprojectnamespace.subfoldername
{
class DoCheckRegularExpression
{
public bool chkregularex(string User_defined_XPath, string User_defined_Xml_file, string User_defined_regularexpression)
{
bool val = false;
try
{
XmlDocument xml_document = new XmlDocument();
xml_document.Load(User_defined_Xml_file);
XmlNodeList nodelist = xml_document.SelectNodes(User_defined_XPath);
foreach (XmlNode node in nodelist)
{
Regex pattern = new Regex(User_defined_regularexpression);
string[] outcome_reg_exp = node.InnerText.Trim().Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in outcome_reg_exp)
{
if (pattern.IsMatch(s))
{
val = true;
return val;
}
else
{
val = false;
}
}
}
}
catch (XmlException)
{
System.Windows.Forms.MessageBox.Show("Please check XML file format" ,"XML file format exception");
}
return val;
}
}
}