How to read data from XML using XPath

Let’s say I want to read bello XML File using XPath

<?xml version="1.0" encoding="UTF-8"?>
<MyConfig>
<name>Vaibhav Shah</name>
<address>Mumbai</address>
</MyConfig>

To read this XML first we need to load this document , which can be done as foolows

// get the file path of input config document.
 string filePath = “Here comes path of your XML file”

_configXmlDoc = new XmlDocument();

// Load input configXml from the file.
 _configXmlDoc.Load(filePath);

After loading the xml file we need to give root node name & after that we need to find nodes in that root node.
This can be done as follows

var xpathQuery = "// MyConfig";

var configRootNode = _configXmlDoc.SelectSingleNode(xpathQuery);

//Extract name
xpathQuery = "./name";
var selectSingleNode1 = configRootNode.SelectSingleNode(xpathQuery);
if (selectSingleNode1 != null)
var myName = selectSingleNode1.InnerText;

//Extract address
xpathQuery = "./EmailFrom";
var xmlNode1 = configRootNode.SelectSingleNode(xpathQuery);
if (xmlNode1 != null)
var myAddress = xmlNode1.InnerText;

Like this we can read data from xml using XPath

admin