LINQ To XML Tutorials with Examples

前端之家收集整理的这篇文章主要介绍了LINQ To XML Tutorials with Examples前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原文地址: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:");
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
@H_502_763@"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:
@H_186_1403@ Section 2: Manipulate XML content and Persist the changes using LINQ To XML
9. Create an XML Document with Xml Declaration/Namespace/Comments using LINQ to XML
When you need to create an XML document containing XML declaration,XML Document Type (DTD) and processing instructions,Comments,Namespaces,you should go in for the XDocument class.
XNamespaceempNM ="urn:lst-emp:emp";
XDocumentxDoc =newXDocument(
newXDeclaration("1.0","UTF-16",null),175)">XElement(empNM +"Employees",175)">XElement("Employee",sans-serif; font-size:13px; text-align:justify"> newXComment("Only 3 elements for demo purposes"),21)">"EmpId",21)">"5"),21)">"Name",21)">"Kimmy"),21)">"Sex",21)">"Female")
)));
StringWritersw =newStringWriter();
xDoc.Save(sw);
Console.WriteLine(sw);
DimempNMAsXNamespace ="urn:lst-emp:emp"
DimxDocAsNewXDocument(NewXDeclaration(Nothing),_
NewXElement(empNM + NewXElement( NewXComment("Female"))))
DimswAsNewStringWriter()
xDoc.Save(sw)
Console.WriteLine(sw)
10. Save the XML Document to a XMLWriter or to the diskusing LINQ to XML
Use the following code to save the XML to a XMLWriter or to your physical disk
XmlWriterxWrite =XmlWriter.Create(sw);
xDoc.Save(xWrite);
xWrite.Close();
// Save to Disk
xDoc.Save("C:\\Something.xml");
@H_502_763@"Saved");
DimxDocAsNewXDocument(NewXDeclaration( DimxWriteAsXmlWriter = XmlWriter.Create(sw)
xDoc.Save(xWrite)
xWrite.Close()
' Save to Disk
xDoc.Save("C:\Something.xml")
Console.WriteLine("Saved")
@H_186_1403@
11. Load an XML Document using XML Reader using LINQ to XML
Use the following code to load the XML Document into an XML Reader
XmlReaderxRead =XmlReader.Create(@"..\\..\\Employees.xml");
XElementxEle =XElement.Load(xRead);
Console.WriteLine(xEle);
xRead.Close();
DimxReadAsXmlReader = XmlReader.Create("..\\..\\Employees.xml")
DimxEleAsXElement = XElement.Load(xRead)
Console.WriteLine(xEle)
xRead.Close()
12. Find Element at a Specific Position using LINQ to XML
Find the 2ndEmployee Element
// Using XElement
"Using XElement");
XElement.Load( varemp1 = xEle.Descendants("Employee").ElementAt(1);
Console.WriteLine(emp);
"------------");
//// Using XDocument
"Using XDocument");
XDocumentxDoc =XDocument.Load( varemp1 = xDoc.Descendants("Employee").ElementAt(1);
Console.WriteLine(emp);
' Using XElement
Console.WriteLine("Using XElement")
DimxEleAsXElement = XElement.Load("..\..\Employees.xml")
Dimemp1 = xEle.Descendants("Employee").ElementAt(1)
Console.WriteLine(emp)
Console.WriteLine("------------")
'// Using XDocument
Console.WriteLine("Using XDocument")
DimxDocAsXDocument = XDocument.Load("..\..\Employees.xml")
Dimemp1 = xDoc.Descendants("Employee").ElementAt(1)
Console.WriteLine(emp)
13. List the First 2 Elements using LINQ to XML
List the details of the first 2 Employees
varemps = xEle.Descendants("Employee").Take(2);
foreach(varempinemps)
Console.WriteLine(emp);
Dimemps = xEle.Descendants("Employee").Take(2)
ForEachempInemps
Console.WriteLine(emp)
Nextemp
14. List the 2nd and 3rd Element using LINQ to XML
List the 2nd and 3rd Employees
@H_502_763@"Employee").Skip(1).Take(2);
Dimemps = xEle.Descendants("Employee").Skip(1).Take(2)
15. List the Last 2 Elements using LINQ To XML
We have been posting the entire elements as output in our prevIoUs examples. Let us say that you want to display only the Employee Name,use this query:
@H_502_763@"Employee").Reverse().Take(2);
Console.WriteLine(emp.Element("EmpId") +""+ emp.Element("Name"));
Dimemps = xEle.Descendants("Employee").Reverse().Take(2)
Console.WriteLine(emp.Element("EmpId") + emp.Element("Name"))
To display only the values without the XML tags,use the ‘Value’ property
foreach(varempinemps)
"EmpId").Value +". "+ emp.Element("Name").Value);
Console.WriteLine(emp.Element("EmpId").Value & ". " & emp.Element("Name").Value)
If you notice,the results are not ordered i.e. the Employee 4 is printed before 3. To order the results,just add call Reverse() again while filtering as shown below:
@H_502_763@"Employee").Reverse().Take(2 ).Reverse();
Dimemps = xEle.Descendants("Employee").Reverse().Take(2 ).Reverse()
16. Find the Element Count based on a condition using LINQ to XML
Count the number of Employees living in the state CA
XElementxelement = varstCnt =fromaddressinxelement.Elements("State") =="CA"
selectaddress;
@H_502_763@"No of Employees living in CA State are {0}",stCnt.Count());
17. Add a new Element at runtime using LINQ to XML
You can add a new Element to an XML document at runtime by using the Add() method of XElement. The new Element gets added as the last element of the XML document.
XElementxEle = xEle.Add(new"George")));
Console.Write(xEle);
DimxEleAsXElement = XElement.Load("..\..\Employees.xml")
xEle.Add(NewXElement( NewXElement("George")))
Console.Write(xEle)
18. Add a new Element as the First Child using LINQ to XML
In the prevIoUs example,by default the new Element gets added to the end of the XML document. If you want to add the Element as the First Child,use the ‘AddFirst()’ method
xEle.AddFirst(new xEle.AddFirst(NewXElement( Console.Write(xEle)
19. Add an attribute to an Element using LINQ to XML
To add an attribute to an Element,use the following code:
xEle.Add(new"Phone",21)">"423-555-4224",newXAttribute("Type",21)">"Home"))));
NewXAttribute("Home"))))
Console.Write(xEle)
20. Replace Contents of an Element/Elements using LINQ to XML
Let us say that in the XML file,you want to change the Country from “USA” to “United States of America” for all the Elements. Here’s how to do so:
varcountries = xEle.Elements("Employee").Elements("Address").Elements("Country").ToList();
foreach(XElementcEleincountries)
cEle.ReplaceNodes("United States Of America");
Dimcountries = xEle.Elements("Country").ToList()
ForEachcEleAsXElementIncountries
"United States Of America")
NextcEle
21. Remove an attribute from all the Elements using LINQ to XML
Let us say if you want to remove the Type attribute ( <Phone Type=”Home”>) attribute for all the elements,then here’s how to do it.
varphone = xEle.Elements("Phone").ToList();
XElementpEleinphone)
pEle.RemoveAttributes();
Dimphone = xEle.Elements("Phone").ToList()
ForEachpEleAsXElementInphone
pEle.RemoveAttributes()
NextpEle
To remove attribute of one Element based on a condition,traverse to that Element andSetAttributeValue("Type",null); You can also use SetAttributeValue(XName,object) to update an attribute value.
22. Delete an Element based on a condition using LINQ to XML
If you want to delete an entire element based on a condition,here’s how to do it. We are deleting the entire Address Element
varaddr = xEle.Elements("Employee").ToList();
XElementaddEleinaddr)
addEle.SetElementValue("Address",null);
Dimaddr = xEle.Elements("Employee").ToList()
ForEachaddEleAsXElementInaddr
Nothing)
NextaddEle
SetElementValue() can also be used to Update the content of an Element.
23. Remove ‘n’ number of Elements using LINQ to XML
If you have a requirement where you have to remove ‘n’ number of Elements; For E.g. To remove the last 2 Elements,then here’s how to do it
varemps = xEle.Descendants("Employee");
emps.Reverse().Take(2).Remove();
DimxEleAsXElement = XElement.Load( Dimemps = xEle.Descendants( emps.Reverse().Take(2).Remove()
24. Save/Persists Changes to the XML using LINQ to XML
All the manipulations we have done so far were in the memory and were not persisted in the XML file. If you have been wondering how to persist changes to the XML,once it is modified,then here’s how to do so. It’s quite simple. You just need to call the Save() method. It’s also worth observing that the structure of the code shown below is similar to the structure of the end result (XML document). That’s one of the benefits of LINQ to XML,that it makes life easier for developers by making it so easy to create and structure XML documents.
@H_502_763@"George"),21)">"Male"),21)">"Home")),21)">"424-555-0545",21)">"Work")),21)">"Street",21)">"Fred Park,East Bay"),21)">"City",21)">"Acampo"),21)">"State",21)">"CA"),21)">"Zip",21)">"95220"),21)">"Country",21)">"USA"))));
xEle.Save(Console.WriteLine(xEle);
Console.ReadLine();
@H_502_763@"USA"))))
Console.WriteLine(xEle)
Console.ReadLine()

Well with that,we conclude this long article of some 'How Do I' operations while using LINQ to XML. Through this article,we have only attempted to scratch the surface of what can be done using LINQ to XML. LINQ to XML is an amazing API and I hope this set of examples has demonstrated that. Theentire sourceof the article in C# and VB.NET can be downloaded overhere. The VB.NET code has been translated using aC# to VB.NET Converting tool.

原文链接:https://www.f2er.com/xml/298517.html

猜你在找的XML相关文章