原文地址: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
@H_502_763@"List of all Employee Names along with their ID:");