TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

How to Select Xml Element Nodes From An Xml File using Xpath - C#,VB.NET

Sample code in C# and VB.NET to Select Xml Element Nodes From An Xml File using Xpath expression.

 Given an XML file,how to access the individual node element values.See the sample code given below.

Consider the XML file below,

<?xml version="1.0" encoding="utf-8"?>
<Employees>
  <Employee ID="E001">
    <Name>Sam</Name>
    <DOB>10/10/1960</DOB>
   </Employee>
  <Employee ID="E002">
    <Name>Peter</Name>
    <DOB>10/10/1980</DOB>
  </Employee>
  <Employee ID="E003">
    <Name>Thomas</Name>
    <DOB>10/01/1970</DOB>    
  </Employee>
</Employees>
 

C#.NET

class Program
    {
        static void Main(string[] args)
        {
            XmlDocument xmlDoc = new XmlDocument();
           
xmlDoc .Load(@"E:\Demos\XmlParsersUnleashed\XmlParsersUnleashed\Employees.xml");

            GetElementValues(xml);
        }

        private static void GetElementValues(XmlDocument
xmlDoc )
        {
            XmlNodeList employeeNodeList =
xmlDoc .SelectNodes("/Employees/Employee");
            foreach (XmlNode xmlNode in employeeNodeList)
            {
                Console.WriteLine("Name :" + xmlNode["Name"].InnerText + "; Date Of Birth :" + xmlNode["DOB"].InnerText);
            }
            Console.Read();
        }
    }

 

VB.NET

Class Program
    Private Shared Sub Main(args As String())
        Dim
xmlDoc As New XmlDocument()
       
xmlDoc .Load("E:\Demos\XmlParsersUnleashed\XmlParsersUnleashed\Employees.xml")

        GetElementValues(
xmlDoc )
    End Sub

    Private Shared Sub GetElementValues(
xmlDoc As XmlDocument)
        Dim employeeNodeList As XmlNodeList =
xmlDoc.SelectNodes("/Employees/Employee")
        For Each xmlNode As XmlNode In employeeNodeList
            Console.WriteLine(("Name :" + xmlNode("Name").InnerText & "; Date Of Birth :") + xmlNode("DOB").InnerText)
        Next
        Console.Read()
    End Sub
End Class

 

 

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading