How to check whether user defined XPath is present in XML file or not?


With the help of this code, finding XPath becomes very easy. Code has been developed in C# whereas application is windows based. You can customize this code if you require complex XPaths. This is used as baseline.

How to check whether user defined XPath is present in XML file or not?

Description -

This sample code is used to check whether user defined XPath is present in XML file or not. User has to give parameters like xpath string and XML file path.



public bool user_defined_XPath_Present_Or_not(string user_defined_XPath_Value, string user_defined_Xml)

{

bool result = false;

try

{

XPathDocument user_xpath_doc = new XPathDocument(user_defined_Xml);

XPathNavigator navigator = user_xpath_doc.CreateNavigator();

XPathNavigator node = navigator.SelectSingleNode(user_defined_XPath_Value);

XmlDocument xpathdoc = new XmlDocument();

xpathdoc.Load(user_defined_Xml);

System.Xml.XmlElement root_node = xpathdoc.DocumentElement;
System.Xml.XmlElement child_node = (System.Xml.XmlElement)root_node.ChildNodes[0].ChildNodes[0];

//It will check rule ./rootname/childname/childname

if (user_defined_XPath_Value == "./" + child_node.LocalName)

{

result = true;
return result;

}

else

{

result = false;
}
if (user_defined_XPath_Value == child_node.LocalName + "/*")

{

if (child_node.HasChildNodes)

{

result = true;

return result;

}

}

else

{

result = false;

}

if (node.HasChildren)

{

result = true;

return result;

}

else

{

result = false;

}

}

catch (Exception)

{

result = false;

}

return 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: