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



<Employees>
<Employee>
<EmpID id="1">1</EmpID>
<EmpName>Chandra</EmpName>
<EmpAddress1>KrishnaLanka</EmpAddress1>
<EmpAddress2>Vijayawada</EmpAddress2>
<City>Vijayawada</City>
<LastUpdatedDate>2010-02-04T14:23:43+05:30</LastUpdatedDate>
<CreateDate>2010-02-04T13:27:12+05:30</CreateDate>

</Employee>
<Employee>
<EmpID id="2">2</EmpID>
<EmpName>Sekhar</EmpName>
<EmpAddress1>KPHB</EmpAddress1>
<EmpAddress2>KPHB</EmpAddress2>
<City>Hyderabad</City>
<LastUpdatedDate>2010-02-04T14:23:43+05:30</LastUpdatedDate>
<CreateDate>2010-02-04T13:27:12+05:30</CreateDate>
</Employee>
</Employees>

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']")

Syntax

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.


Comments

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"
Width="400px">



<%# Eval("Name")%>
 


MaxLength="50">
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:
    Email: