Select XML Node Element Values According to a Specific Attribute Value:This article explains how to select individual XML element value from an XML file according to a specific attribute value using XPath expression.
Consider the XML file below,
<!--?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>
Below samples will help you for accessing the Employee node’s internal elements according to the ID attribute provided.The XPath expression “/Employees/Employee[@ID=’E002′]” is used to fetch the Elements inside Employee element node whose ID attribute value is EOO2
C#.NET Code – Select XML Node Element Values According to a Specific Attribute Value
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\XmlParsersUnleashed\XmlParsersUnleashed\Employees.xml");
GetSingleNodeByAttributeValue(xmlDoc);
}
/// <summary>
/// Performs the parsing and displys the element values
/// </summary>
private static void GetSingleNodeByAttributeValue(XmlDocument xmlDoc)
{
//execute the xpath expression "/Employees/Employee[@ID='E002']" which selects
//the Employee element with attribute ID's value 'E002'
XmlNode employeeNode = xmlDoc.SelectSingleNode("/Employees/Employee[@ID='E002']");
Console.WriteLine("Name :" + employeeNode["Name"].InnerText);
Console.WriteLine("Date of Birth :" + employeeNode["DOB"].InnerText);
Console.Read();
}
}
VB.NET Code – Select XML Node Element Values According to a Specific Attribute Value
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\XmlParsersUnleashed\XmlParsersUnleashed\Employees.xml")
GetSingleNodeByAttributeValue(xmlDoc)
End Sub
''' <summary>
''' Performs the parsing and displys the element values
''' </summary>
Private Shared Sub GetSingleNodeByAttributeValue(xmlDoc As XmlDocument)
'execute the xpath expression "/Employees/Employee[@ID='E002']" which selects
'the Employee element with attribute ID's value 'E002'
Dim employeeNode As XmlNode = xmlDoc.SelectSingleNode("/Employees/Employee[@ID='E002']")
Console.WriteLine("Name :" + employeeNode("Name").InnerText)
Console.WriteLine("Date of Birth :" + employeeNode("DOB").InnerText)
Console.Read()
End Sub
End Class
Leave a Reply