How to read XML attributes using XPath in c#

In Previous tutorial I showed that how can we read xml node data using XPath
Now we will read attributes data from XML using XPath
Bellow is demo XML file from which we will read XML attribute data.

<?xml version="1.0" encoding="UTF-8"?>
<MyConfig>
<name firstname=”Vaibhav” lastname=”Shah”>V.S.</name>
<address>Mumbai</address>
</MyConfig>

As shown in previous tutorial we need to load document, then read root node & then read node which we want to read.

// 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);

var xpathQuery = "// MyConfig";

var configRootNode = _configXmlDoc.SelectSingleNode(xpathQuery);

//Extract name
xpathQuery = "./name";

 var selectSingleNode1 = configRootNode.SelectSingleNode(xpathQuery);
 if (selectSingleNode1 != null)
 var myName = selectSingleNode1.InnerText;

Now we will read attribute from node “name”

var firstName = selectSingleNode1.Attributes != null && (selectSingleNode1.Attributes.GetNamedItem("firstname") != null)
                ? selectSingleNode1.Attributes.GetNamedItem ("firstname").Value
                : string.Empty;

In above code what we do is that we define condition that if node “name” has attribute & attribute “firstname” is not null then get the data from that attribute else pass empty string.
Like this we can read data for attribute “lastname” also.

var lastname =  selectSingleNode1.Attributes != null && (selectSingleNode1.Attributes.GetNamedItem("lastname") != null)
                ? selectSingleNode1.Attributes.GetNamedItem ("lastname").Value
                : string.Empty;

admin

  • puneet

    hi,

    what is _configXmlDoc in above code. And what is its role.