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.
It is a very useful post!!!
Thanks for sharing