How to check whether attribute is present or not in XPath in xml file.


There is a sample code to check whether the attribute is present in XPath in xml file or not. User can set xpath , attribute and xml file dynamically to check this. Code has been developed in C# whereas application is windows based.

How to check whether attribute is present or not in XPath in xml file.
Description -
Create a class library which will check whether the attribute is present in XPath in xml file. For e.g There is one xml file say test.xml in which xpath will be //studentsList/student then suppose user needs to find "firstname" as an attribute which is present in //studentsList/student of test.xml then
user has to give parameters such as firstname i.e. name of the parameter , test.xml i.e. xml file name , //studentsList/student i.e. xpath in xml
Use following code for the same -


public bool Attribute_Present_Or_not(string user_defined_attribute, string user_defined_xml_file, string user_defined_xpath)
{
bool chk_result = false;

try
{
XmlDocument user_xml_document = new XmlDocument();
user_xml_document.Load(user_defined_xml_file);

XmlNodeList user_nodeList = user_xml_document.SelectNodes(user_defined_xpath);
XmlElement root = user_xml_document.DocumentElement;

foreach (XmlNode user_node in user_nodeList)
{
try{
if (user_node.Attributes.GetNamedItem(user_defined_attribute)!=null)

{
chk_result = true;

return chk_result;
}
}
catch (Exception )
{
chk_result = false;

return chk_result;

}

}

}
catch (NullReferenceException)
{
chk_result = false;

return chk_result;
}
catch (XPathException)
{
chk_result = false;

return chk_result;
}

return chk_result;
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: