In this post, I am explaining how you can access only the specified number of required XML elements using the XPATH expression.The Same sample is given in both C# and VB.NET.
Consider the same XML sample file which I have used for my other sample codes,
<!--?xml version="1.0" encoding="utf-8"?-->
<Employee>
<Name>Sam</Name>
<DOB>10/10/1960</DOB>
<Name>Peter</Name>
<DOB>10/10/1980</DOB>
<Name>Thomas</Name>
<DOB>10/01/1970</DOB>
</Employee>
Table of Contents
Select Required Number of Nodes From Top or Bottom Using XPATH
In the below given sample it is accessing the Employee elements which are at position above level 1 in the selected XML Element order. Similarly you can access first n element, last n elements or any of that sort according to the position.
C# – Select Required nodes using XPATH
class Program
{
static void Main(string[] args)
{
XmlDocument xmlDoc = new XmlDocument();
//Hardcoded path is the xml file path.Set it to your xml file path.
xmlDoc.Load(@"E:\Demos\Employees.xml");
// Call the method which parses and displays the elements as per the xpath expression
GetElementsByPosition(xmlDoc);
}
///
/// Get Xml elements by their position in xml element hierarchy and display the result
///
///
private static void GetElementsByPosition(XmlDocument xmlDoc)
{
//Selects the Employee elements from employee parent node where order of the <br>
//Employee element in XML is greater than 1.
XmlNodeList employeeNodeList = xmlDoc.SelectNodes("/Employees/Employee[position() > 1]");
foreach (XmlNode xmlNode in employeeNodeList)
{
Console.WriteLine("Name :" + xmlNode["Name"].InnerText);
}
Console.Read();
}
}
VB.NET – Select Required nodes using XPATH
Class Program
Private Shared Sub Main(args As String())
Dim xmlDoc As New XmlDocument()
'Hardcoded path is the xml file path.Set it to your xml file path.
xmlDoc.Load("E:\Demos\Employees.xml")
'Call the method which parses and displays the elements as per the xpath expression
GetElementsByPosition(xmlDoc)
End Sub
'''
''' Get Xml elements by their position in xml element hierarchy and display the result
'''
'''
Private Shared Sub GetElementsByPosition(xmlDoc As XmlDocument)
'Selects the Employee elements from employee parent node where order of the <br>
'employee element in XML is greater than 1.
Dim employeeNodeList As XmlNodeList = xmlDoc.SelectNodes("/Employees/Employee[position() > 1]")
For Each xmlNode As XmlNode In employeeNodeList
Console.WriteLine("Name :" + xmlNode("Name").InnerText)
Next
Console.Read()
End Sub
End Class
Summary
This post covered on XPATH for Selecting Required Number Of Nodes From Top or Bottom Using C# and VB.NET. Hope you found this article useful. Leave your views and feedback.
Leave a Reply