There are three ways to read XML files in C#: XDocument, XmlDocument and DataSet. First, using XDocument can queries and manipulate XML data concisely and efficiently through LINQ, which is suitable for scenarios with clear structures and flexible queries; second, using XmlDocument is an old and stable DOM parsing method that supports XPath query, which is suitable for situations where nested structures are complex or need to be compatible with old code; third, using DataSet is suitable for XML files with similar database tables, which can be directly mapped into a table structure, but is not suitable for data with deep nesting levels; in addition, pay attention to checking file path problems, and it is recommended to use Path.Combine() to splice the path to avoid errors.
Reading XML files is a common task in C#, especially when handling configuration files, data exchange, or Web service responses. You can do this using a variety of categories provided by .NET, such as XmlDocument
, XDocument
, or DataSet
. Here are some practical methods and suggestions.

Use XDocument to be simple and efficient
If you want to query and manipulate XML data in LINQ, it is recommended to use System.Xml.Linq.XDocument
. It is part of LINQ to XML, with concise syntax and powerful functions.
Basic usage:

using System.Xml.Linq; XDocument doc = XDocument.Load("example.xml"); foreach (var item in doc.Descendants("Item")) { string name = item.Element("Name").Value; Console.WriteLine(name); }
- Suitable for scenarios with clear structure and flexible query.
- If you are familiar with LINQ, this method will be very easy.
- Note that you want to add a reference to
System.Xml.Linq
.
Use XmlDocument old but stable
XmlDocument
is a traditional DOM method to parse XML. Although the writing method is relatively cumbersome, it is still common in some old projects.
Sample code:

using System.Xml; XmlDocument doc = new XmlDocument(); doc.Load("example.xml"); XmlNodeList nodes = doc.SelectNodes("/Root/Items/Item"); foreach (XmlNode node in nodes) { Console.WriteLine(node["Name"].InnerText); }
- Supports XPath query, good flexibility.
- It is more suitable for situations where nested structures are complex or if you need to be compatible with old code.
- The disadvantage is that it is verbose to write and its performance is slightly inferior to XDocument.
Use DataSet to map directly to a tabular structure
If your XML file structure is similar to a database table (such as the concept of rows and columns), you can consider using DataSet
to load it.
example:
DataSet ds = new DataSet(); ds.ReadXml("example.xml"); foreach (DataRow row in ds.Tables[0].Rows) { Console.WriteLine(row["Name"]); }
- Especially suitable for exporting and importing structured data.
- There are certain requirements for the XML format and cannot be too complicated.
- Not suitable for data structures with deep nesting levels.
Tips: XML file path problems are prone to errors
- An incorrect path is one of the most common mistakes, remember to check if the file exists.
- You can use
AppDomain.CurrentDomain.BaseDirectory
to get the current program running directory. - Or use
Path.Combine()
to splice the path to avoid errors caused by manual splicing.
For example:
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "example.xml");
Basically these are the methods. Which one to choose depends on your specific needs: if you pursue modern simplicity, use XDocument
, use XmlDocument
to be compatible with old code, and try DataSet
structure like tables.
The above is the detailed content of How to read an XML file 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

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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)

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

In Unity, 3D physics engines and AI behavior trees can be implemented through C#. 1. Use the Rigidbody component and AddForce method to create a scrolling ball. 2. Through behavior tree nodes such as Patrol and ChasePlayer, AI characters can be designed to patrol and chase players.

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

The main differences between C# and C are memory management, polymorphism implementation and performance optimization. 1) C# uses a garbage collector to automatically manage memory, while C needs to be managed manually. 2) C# realizes polymorphism through interfaces and virtual methods, and C uses virtual functions and pure virtual functions. 3) The performance optimization of C# depends on structure and parallel programming, while C is implemented through inline functions and multithreading.

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.
