Frequently, the most of people use XPATH to do xml manipulation. But if you want another way to manipulate XML, you can use LINQ to XML.
Supposing that we have the following XML:
<?xml version="1.0" encoding="utf-8"?><ArrayOfEmployee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><Employee Status="Active"><FirstName>John</FirstName><LastName>Smith</LastName><Age>32</Age><EmployeeNumber>213</EmployeeNumber></Employee><Employee Status="Inactive"><FirstName>Mike</FirstName><LastName>Stuart</LastName><Age>24</Age><EmployeeNumber>253</EmployeeNumber></Employee><Employee Status="Inactive"><FirstName>John</FirstName><LastName>Charles</LastName><Age>53</Age><EmployeeNumber>214</EmployeeNumber></Employee><Employee Status="Active"><FirstName>Mary</FirstName><LastName>Gomez</LastName><Age>37</Age><EmployeeNumber>234</EmployeeNumber></Employee><Employee Status="Inactive"><FirstName>Javier</FirstName><LastName>Matias</LastName><Age>33</Age><EmployeeNumber>453</EmployeeNumber></Employee></ArrayOfEmployee>You can filter an employee with a specified employee number (by Element).
- Code:
Console.WriteLine("Employee with employee number 213:");
XDocument xDoc = XDocument.Load("AllEmployes.xml");
XElement employeeUser = xDoc.Descendants("Employee")
.Where(e => e.Element("EmployeeNumber").Value.Equals("213"))
.Single();
Console.WriteLine(string.Format("{0} {1} - {2}",
employeeUser.Element("FirstName").Value,
employeeUser.Element("LastName").Value,
employeeUser.Element("EmployeeNumber").Value));
- Result:
You can filter all active employees (by Attribute).
- Code:
Console.WriteLine("Get all active employees:");
List<XElement> allActiveEmployees = xDoc.Descendants("Employee")
.Where(e => e.Attribute("Status").Value.Equals("Active"))
.ToList();
foreach (XElement employee in allActiveEmployees)
{
Console.WriteLine(string.Format("{0} {1} - {2}",
employee.Element("FirstName").Value,
employee.Element("LastName").Value,
employee.Element("EmployeeNumber").Value));
}
- Result: