In C#, you can read XML files using the System.Xml namespace, which provides classes like
XmlDocument, XmlTextReader, and XDocument for parsing and working with XML data. Here, I'll provide a sample using both
XmlDocument and XDocument to read an XML file:
using System;
using System.Xml;
class Program
{
static void Main()
{
// Load the XML file
XmlDocument doc = new XmlDocument();
doc.Load("example.xml");
// Select the root node
XmlNode root = doc.DocumentElement;
// Select child nodes
XmlNodeList personNodes = root.SelectNodes("person");
// Iterate through the person nodes
foreach (XmlNode personNode in personNodes)
{
string name = personNode.SelectSingleNode("name").InnerText;
int age = int.Parse(personNode.SelectSingleNode("age").InnerText);
Console.WriteLine($"Name: {name}, Age: {age}");
}
}
}
Reading XML using XDocument (LINQ to XML):
using System;
using System.Linq;
using System.Xml.Linq;
class Program
{
static void Main()
{
// Load the XML file
XDocument doc = XDocument.Load("example.xml");
// Query elements using LINQ to XML
var persons = from person in doc.Descendants("person")
select new
{
Name = (string)person.Element("name"),
Age = (int)person.Element("age")
};
// Iterate through the selected elements
foreach (var person in persons)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
}
}
}
Both XmlDocument and XDocument provide methods for loading and querying XML data.
XDocument is part of LINQ to XML and is often preferred for its simplicity and integration with LINQ. Choose the one that best fits your needs and coding style.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In C#, you can read XML files using the System.Xml namespace, which provides classes like XmlDocument, XmlTextReader, and XDocument for parsing and working with XML data. Here, I'll provide a sample using both XmlDocument and XDocument to read an XML file:
Sample XML File (example.xml):
Reading XML using XmlDocument:
Reading XML using XDocument (LINQ to XML):
Both XmlDocument and XDocument provide methods for loading and querying XML data. XDocument is part of LINQ to XML and is often preferred for its simplicity and integration with LINQ. Choose the one that best fits your needs and coding style.