原文地址:http://www.dotnetcurry.com/showarticle.aspx?ID=564
A lot of developers over the past few months have requested us for tutorials focusing on LINQToXML. Although I have written a couple of them in the past,I decided to republish these tips in the form of a single post. In this article,we will explore 24 ‘How Do I’ kind of examples using LINQ to XML. I assume you are familiar with LINQ. If not,you can start off with LINQ by checking some tutorials over
here
and
here
.
Subscribe to our Free Digital Magazines for .NET Professionals
For this article,we will be using a sample file called ‘Employees.xml’ for all our samples which is available with the
source code
. So make sure you keep it handy with you while are practicing these examples. The mark up for Employees.xml is as follows:
<?xmlversion="1.0"encoding="utf-8"?>
<Employees>
Employee>
<EmpId>1</EmpId>
Name>Sam</Name>
Sex>Male</Sex>
PhoneType="Home">423-555-0124</Phone>
PhoneType="Work">424-555-0545</Address>
Street>7A Cox Street</Street>
City>Acampo</City>
State>CA</State>
Zip>95220</Zip>
Country>USA</Country>
</
</EmpId>2</Name>Lucy</Sex>Female</PhoneType="Home">143-555-0763</PhoneType="Work">434-555-0567</Street>Jess Bay</City>Alta</Zip>95701</EmpId>3</Name>Kate</PhoneType="Home">166-555-0231</PhoneType="Work">233-555-0442</Street>23 Boxen Street</City>Milford</Zip>96121</EmpId>4</Name>Chris</PhoneType="Home">564-555-0122</PhoneType="Work">442-555-0154</Street>124 Kutbay</City>Montara</Zip>94037</
The application is a console application targeting .NET 3.5 framework,although you can use the latest .NET 4.0 framework too. I have also used ‘query expressions’,instead of Lambda expression in these samples. It is just a matter of preference and you are free to use any of these.
This tutorial has been divided into 2 sections:
Section 1: Read XML and Traverse the Document using LINQ To XML
Section 2: Manipulate XML content and Persist the changes using LINQ To XML
The following namespaces are needed while testing the samples: System;System.Collections.Generic; System.Linq; System.Text; System.Xml; System.Xml.Linq;
Go grab a hot cup of coffee,put on your developer cap and let us get started:
Section 1: Read XML and Traverse the XML Document using LINQ To XML
1. How Do I Read XML using LINQ to XML
There are two ways to do so: Using the XElement class or the XDocument class. Both the classes contain the ‘Load()’ method which accepts a file,a URL or XMLReader and allows XML to be loaded. The primary difference between both the classes is that an XDocument can contain XML declaration,XML Document Type (DTD) and processing instructions. Moreover an XDocument contains one root XElement.
Using XElement
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
// Read the entire XML
foreach(varemployeeinemployees)
{
Console.WriteLine(employee);
}
VB.NET (Converted Code)
DimxelementAsXElement = XElement.Load("..\..\Employees.xml")
DimemployeesAsIEnumerable(OfXElement) = xelement.Elements()
' Read the entire XML
ForEachemployeeInemployees
Console.WriteLine(employee)
Nextemployee
Output:
Using XDocument
XDocumentxdocument = XDocument.Load(XElement> employees = xdocument.Elements();
Console.WriteLine(employee);
}
DimxdocumentAsXDocument = XDocument.Load("..\..\Employees.xml")
DimemployeesAsIEnumerable(OfXElement) = xdocument.Elements()
Note 1: As you can observe,XDocument contains a single root element (Employees).
Note 2: In order to generate an output similar to the one using XElement,use “xdocument.Root.Elements()” instead of “xdocument.Elements()”
Note 3: VB.NET users can use a new feature called XML Literal.
2. How Do I Access a Single Element using LINQ to XML
Let us see how to access the name of all the Employees and list them over here
XElementxelement = XElement.Load(Console.WriteLine("List of all Employee Names :");
Console.WriteLine(employee.Element("Name").Value);
Console.WriteLine("List of all Employee Names :")
Console.WriteLine(employee.Element("Name").Value)
3. How Do I Access Multiple Elements using LINQ to XML
Let us see how to access the name of all Employees and also list the ID along with it
"List of all Employee Names along with their ID:");
Console.WriteLine("{0} has Employee ID {1}",
employee.Element("Name").Value,21)">"EmpId").Value);
Console.WriteLine("List of all Employee Names along with their ID:")
Console.WriteLine("{0} has Employee ID {1}",employee.Element("Name").Value,employee.Element("EmpId").Value)
4. How Do I Access all Elements having a Specific Attribute using LINQ to XML
Let us see how to access details of all Female Employees
varname =fromnminxelement.Elements("Employee")
where(string)nm.Element("Sex") =="Female"
selectnm;
"Details of Female Employees:");
foreach(XElementxEleinname)
Console.WriteLine(xEle);
Dimname = _
From nmInxelement.Elements("Employee") _
WhereCStr(nm.Element("Sex")) = "Female" _
Selectnm
Console.WriteLine("Details of Female Employees:")
ForEachxEleAsXElementInname
Console.WriteLine(xEle)
NextxEle
5. How Do I access Specific Element having a Specific Attribute using LINQ to XML
Let us see how to list all the Home Phone Nos.
varhomePhone =fromphonenoinxelement.Elements(
where(string)phoneno.Element("Phone").Attribute("Type") =="Home"
selectphoneno;
"List HomePhone Nos.");
XElementxEleinhomePhone)
Console.WriteLine(xEle.Element("Phone").Value);
DimhomePhone = _
From phonenoInxelement.Elements("Employee") _
WhereCStr(phoneno.Element("Phone").Attribute("Type")) = "Home" _
Selectphoneno
Console.WriteLine("List HomePhone Nos.")
ForEachxEleAsXElementInhomePhone
Console.WriteLine(xEle.Element("Phone").Value)
6. How Do I Find an Element within another Element using LINQ to XML
Let us see how to find the details of Employees living in 'Alta' City
varaddresses =fromaddressinxelement.Elements(
where(string)address.Element("Address").Element("City") =="Alta"
selectaddress;
"Details of Employees living in Alta City");
XElementxEleinaddresses)
Dimaddresses = _
From addressInxelement.Elements("Employee") _
WhereCStr(address.Element("Address").Element("City")) = "Alta" _
Selectaddress
Console.WriteLine("Details of Employees living in Alta City")
ForEachxEleAsXElementInaddresses
7. How Do I Find Nested Elements (using Descendants Axis) using LINQ to XML
Let us see how to list all the zip codes in the XML file
"List of all Zip Codes");
XElementxEleinxelement.Descendants("Zip"))
Console.WriteLine((string)xEle);
Console.WriteLine("List of all Zip Codes")
ForEachxEleAsXElementInxelement.Descendants("Zip")
Console.WriteLine(CStr(xEle))
8. How do I apply Sorting on Elements using LINQ to XML
Let us see how to List and Sort all Zip Codes in ascending order
IEnumerable<string> codes =fromcodeinxelement.Elements(
letzip = (string)code.Element("Zip")
orderbyzip
selectzip;
"List and Sort all Zip Codes");
foreach(stringzpincodes)
Console.WriteLine(zp);
DimcodesAsIEnumerable(OfString) = _
From codeInxelement.Elements("Employee") _
Letzip =CStr(code.Element("Address").Element("Zip")) _
Order By zip _
Selectzip
Console.WriteLine("List and Sort all Zip Codes")
ForEachzpAsStringIncodes
Console.WriteLine(zp)
Nextzp
Output: