XPath expression to get elements of an XML File/String

Xpath expression can be used in any language to access particula element/node of an xml document.

Here is Sample XML

<EmpID id="1">1</EmpID>

<EmpID id="2">2</EmpID>

C-Sharp code to access specific node dierectly using XPath Expression

XmlDocument doc = new XmlDocument();

doc.Load("TestXml1.xml");//Loads xml file
Get employee where Id = 1

XmlNode node = doc.DocumentElement.SelectSingleNode("Employee/EmpID[@id='1']")


XmlNode node = doc.DocumentElement.SelectSingleNode("<ParentElemenetName>/<ElementName>[@<AttributeName>='<Value to compare>']")

Placing @ before attribute name is madatory

If multiple nodes matching with given value exists in xml file then only first node will be returned

If we want to get all the nodes which match to the given criteria user "SelectNodes" method to get Nodes list

If not match found then it returns null.

Note:Attribute names and node names are case sensitive

To get all nodes of type EmpID (Employee Id) then

XmlNodeList nodeList = doc.DocumentElement.SelectNodes("Employee/EmpID");

To get all nodes of type EmpName (Employee name) then

XmlNodeList nodeList = doc.DocumentElement.SelectNodes("Employee/EmpName");

We can use these XPath expression even in Javascript also.


Author: krishnavenikaladi19 Feb 2010 Member Level: Gold   Points : 0

It is a very useful post!!!
Thanks for sharing

Author: Biju15 Oct 2010 Member Level: Gold   Points : 1

Html backend Code : For grid view:

OnRowEditing="grdData_RowEditing" OnRowUpdating="grdData_RowUpdating" OnRowDeleting="grdData_RowDeleting"
OnPreRender="grdData_PreRender" DataKeyNames="ID" OnRowDataBound="grdData_RowDataBound"

<%# Eval("Name")%>

ValidationGroup="Role" Text="*" ErrorMessage="Name cannot be Blank">
ValidationGroup="Role" Text="*" ErrorMessage="Enter Valid Name" ValidationExpression="^[A-Za-z- ]+$">

<%# Eval("IsDefault")%>

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