How to use LINQ to XML for data manipulation in C#
LINQ to XML enables easy XML manipulation in C# using XDocument and XElement. 1. Load XML via Parse() or Load(). 2. Query with LINQ using Descendants(), Element(), Attribute(), and Value. 3. Modify by adding, updating, or removing nodes. 4. Save via Save() or ToString().

LINQ to XML provides a lightweight, in-memory XML programming interface that lets you query and manipulate XML data directly in C#. It integrates seamlessly with LINQ, making it easy to read, create, modify, and save XML documents using a clean and expressive syntax.
Load and Parse XML Data
You can load XML from a string, file, or stream using XDocument or XElement. These are the core classes in LINQ to XML.
- Use XDocument.Parse() to parse XML from a string.
- Use XDocument.Load() to load XML from a file.
- XElement is useful when working with fragments of XML rather than full documents.
Example:
XDocument doc = XDocument.Parse(@"
<Books>
<Book ID='1'>
<Title>C# in Depth</Title>
<Author>Jon Skeet</Author>
</Book>
<Book ID='2'>
<Title>CLR via C#</Title>
<Author>Jeffrey Richter</Author>
</Book>
</Books>");Query XML Using LINQ
With LINQ to XML, you can use standard LINQ queries to extract data from XML elements and attributes.
- Use Elements() to get child elements.
- Use Attribute() to access attribute values.
- Use Value to retrieve text content.
Example: Retrieve all book titles and authors
var books = from book in doc.Descendants("Book")
select new
{
ID = (int)book.Attribute("ID"),
Title = book.Element("Title")?.Value,
Author = book.Element("Author")?.Value
};
<p>foreach (var b in books)
{
Console.WriteLine($"ID: {b.ID}, Title: {b.Title}, Author: {b.Author}");
}Modify XML Data
LINQ to XML allows you to add, update, or remove elements and attributes in place.
- Add new elements using Add().
- Change values by assigning to Value or Attribute().
- Remove elements or attributes using Remove().
Example: Add a new book
doc.Root?.Add(
new XElement("Book", new XAttribute("ID", "3"),
new XElement("Title", "Programming C#"),
new XElement("Author", "Ian Griffiths")
)
);Example: Update an existing book's author
var bookToUpdate = doc.Descendants("Book")
.FirstOrDefault(b => (int)b.Attribute("ID") == 1);
if (bookToUpdate != null)
{
bookToUpdate.Element("Author")!.Value = "Updated Author";
}Save XML to File or String
After manipulation, you can output the XML back to a file or string.
- Use doc.Save("path.xml") to write to a file.
- Use doc.ToString() to get XML as a string.
Example:
doc.Save("books_updated.xml");
string xmlString = doc.ToString();Basically, LINQ to XML simplifies working with XML by combining the power of LINQ with intuitive object models. You don't need to deal with complex readers or writers—just load, query, edit, and save using familiar C# syntax.
The above is the detailed content of How to use LINQ to XML for data manipulation in C#. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20516
7
13629
4
How to read app settings from appsettings.json in C#?
Sep 15, 2025 am 02:16 AM
The answer is to read appsettings.json using Microsoft.Extensions.Configuration. 1. Create appsettings.json and set the copy properties; 2. Install the Microsoft.Extensions.Configuration.Json package; 3. Load the configuration with ConfigurationBuilder; 4. Read the value through the indexer or GetConnectionString; 5. It is recommended to use strongly typed configuration classes Bind or Get binding.
What are the different access modifiers in C#?
Sep 21, 2025 am 01:43 AM
Public members can be accessed by any code; 2.private is only accessible within the class; 3.protected allows access to classes and derived classes; 4.internal is limited to access within the same assembly; 5.protectedinternal is a union of protected and internal, used for access to derived classes or same assembly.
How to create and use a CancellationToken in C#?
Sep 21, 2025 am 01:49 AM
Create a CancellationTokenSource to get the CancellationToken, which is used to notify other threads or components to cancel the operation. 2. Pass the token to an asynchronous method that supports cancellation (such as Task.Run). The task can periodically check the cancellation request to achieve graceful termination.
C# IEnumerable vs ICollection vs IList.
Sep 22, 2025 am 03:47 AM
IEnumerable is the basic traversal interface that supports delayed execution; ICollection adds Count and add-and-deletion operations; IList further supports index access and position insertion. Selection principle: Only use IEnumerable for traversal, use ICollection for modification, and index IList. The return type should be abstracted as much as possible to improve flexibility.
How to debug a C# application in VSCode
Sep 17, 2025 am 08:47 AM
To debug C# applications, you need to first install the C# extension of .NETSDK and VSCode, then generate or configure the launch.json file, set breakpoints and press F5 to start debugging, to ensure that the project is built in Debug mode and the output path is correct, and finally check the variables and execution process through the debugging tool. The entire process becomes simple and efficient after the configuration is completed.
How to parse JSON in C#?
Sep 14, 2025 am 01:34 AM
UseSystem.Text.Jsonfor.NETCore3.0 withJsonSerializer.Deserialize()toparseJSONintoadefinedclasslikePerson.2.Formorefeatures,useNewtonsoft.JsonviaJsonConvert.DeserializeObject().3.FordynamicJSON,useJsonDocumentwithSystem.Text.JsonorJObjectwithNewtonsof
What is the purpose of the in parameter modifier in C#?
Sep 20, 2025 am 06:29 AM
TheinparametermodifierinC#enablespass-by-referencewithimmutability,improvingperformancewhenpassinglargestructswithoutallowingmodification.Itavoidscostlycopies,ensurestheparametercannotbechangedwithinthemethod,andisidealforperformance-criticalscenario
What is a Predicate delegate in C#?
Sep 23, 2025 am 12:26 AM
Predicate is a generic delegate that returns a Boolean value, used to define conditional judgments, and is often used for filtering operations of collections, such as the FindAll method, which is equivalent to Func, but has clearer semantics.





