C# XML Examples
C# Basic
C# Data Type
C# OOP
C# IO
C# Graphics & UI
C# Advanced
How to read and parse an XML file in C#:
To read and parse an XML file in C#, you can use the System.Xml
namespace which provides several classes to work with XML files. Here is an example:
using System.Xml; // Load the XML document XmlDocument doc = new XmlDocument(); doc.Load("path/to/xmlfile.xml"); // Select the root node XmlNode root = doc.SelectSingleNode("/root"); // Loop through child nodes foreach (XmlNode node in root.ChildNodes) { // Get the node values string id = node.SelectSingleNode("id").InnerText; string name = node.SelectSingleNode("name").InnerText; string description = node.SelectSingleNode("description").InnerText; // ... }
In this example, we load the XML file using the XmlDocument
class and select the root node using SelectSingleNode
method. Then, we loop through the child nodes of the root node and get the values of each node using the SelectSingleNode
method again.
How to deserialize only part of an XML document in C#:
To deserialize only part of an XML document in C#, you can use the XmlSerializer
class. Here is an example:
using System.Xml.Serialization; using System.IO; // Define the class to deserialize public class Item { public string Id { get; set; } public string Name { get; set; } public string Description { get; set; } // ... } // Load the XML document XmlDocument doc = new XmlDocument(); doc.Load("path/to/xmlfile.xml"); // Select the node to deserialize XmlNode node = doc.SelectSingleNode("/root/item"); // Deserialize the node XmlSerializer serializer = new XmlSerializer(typeof(Item)); Item item; using (var reader = new StringReader(node.OuterXml)) { item = (Item)serializer.Deserialize(reader); } // Use the deserialized object string id = item.Id; string name = item.Name; string description = item.Description; // ...
In this example, we define a class called Item
that matches the structure of the XML node we want to deserialize. Then, we load the XML document using the XmlDocument
class and select the node to deserialize using SelectSingleNode
method. After that, we create an instance of the XmlSerializer
class for the Item
type and deserialize the node using the Deserialize
method. Finally, we use the deserialized object to get the values of its properties.
To read an XML file as an embedded resource in C#, you can use the System.Reflection
namespace along with the System.IO
namespace.
Here's an example:
using System.Reflection; using System.IO; using System.Xml; // Assume that the XML file is named "example.xml" and is located in the project's "Resources" folder var assembly = Assembly.GetExecutingAssembly(); var resourceName = "YourProjectName.Resources.example.xml"; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(stream)) { string result = reader.ReadToEnd(); // Do something with the XML content here }
To convert an XML string to a DataTable in C#, you can use the System.Data.DataSet
class.
Here's an example:
using System.Data; string xmlString = "<Root><Row><Column1>Value1</Column1><Column2>Value2</Column2></Row><Row><Column1>Value3</Column1><Column2>Value4</Column2></Row></Root>"; DataSet dataSet = new DataSet(); dataSet.ReadXml(new StringReader(xmlString)); DataTable dataTable = dataSet.Tables[0]; // Do something with the DataTable here
In this example, the XML string is read into a DataSet
using the ReadXml
method, and then the first DataTable
in the DataSet
is extracted for further processing.
C# XML deserialization example:
Deserializing XML data into a .NET object using XmlSerializer
.
using System; using System.IO; using System.Xml.Serialization; // Example class for deserialization [Serializable] public class Person { public string Name { get; set; } public int Age { get; set; } } class Program { static void Main() { // XML data string xmlData = "<Person><Name>John Doe</Name><Age>30</Age></Person>"; // Deserialize XML to object Person person; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(Person)); person = (Person)serializer.Deserialize(reader); } // Use the deserialized object Console.WriteLine($"Name: {person.Name}, Age: {person.Age}"); } }
Deserialize XML to object in C#:
Deserializing XML content into a custom object using XmlSerializer
.
using System; using System.IO; using System.Xml.Serialization; [Serializable] public class Product { public string Name { get; set; } public double Price { get; set; } } class Program { static void Main() { string xmlData = "<Product><Name>Laptop</Name><Price>999.99</Price></Product>"; Product product; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(Product)); product = (Product)serializer.Deserialize(reader); } Console.WriteLine($"Product: {product.Name}, Price: ${product.Price}"); } }
Using XmlSerializer in C# for XML deserialization:
Utilizing XmlSerializer
for deserialization with attributes.
using System; using System.IO; using System.Xml.Serialization; [Serializable] public class Book { [XmlAttribute("Title")] public string Title { get; set; } [XmlElement("Author")] public string Author { get; set; } [XmlElement("Price")] public double Price { get; set; } } class Program { static void Main() { string xmlData = "<Book Title='The C# Book'><Author>John Doe</Author><Price>29.99</Price></Book>"; Book book; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(Book)); book = (Book)serializer.Deserialize(reader); } Console.WriteLine($"Book: {book.Title}, Author: {book.Author}, Price: ${book.Price}"); } }
C# XML deserialization attributes: Applying XML serialization attributes for customizing deserialization.
using System; using System.IO; using System.Xml.Serialization; [XmlRoot("Student")] public class Student { [XmlAttribute("ID")] public int StudentID { get; set; } [XmlElement("Name")] public string FullName { get; set; } [XmlElement("Grade")] public char Grade { get; set; } } class Program { static void Main() { string xmlData = "<Student ID='123'><Name>Jane Doe</Name><Grade>A</Grade></Student>"; Student student; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(Student)); student = (Student)serializer.Deserialize(reader); } Console.WriteLine($"Student ID: {student.StudentID}, Name: {student.FullName}, Grade: {student.Grade}"); } }
Deserializing nested XML elements in C#: Handling nested XML elements during deserialization.
using System; using System.IO; using System.Xml.Serialization; [Serializable] public class Department { public string Name { get; set; } [XmlElement("Employee")] public Employee[] Employees { get; set; } } [Serializable] public class Employee { public string FullName { get; set; } public int EmployeeID { get; set; } } class Program { static void Main() { string xmlData = "<Department><Name>IT</Name><Employee><FullName>John Doe</FullName><EmployeeID>101</EmployeeID></Employee><Employee><FullName>Jane Smith</FullName><EmployeeID>102</EmployeeID></Employee></Department>"; Department department; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(Department)); department = (Department)serializer.Deserialize(reader); } Console.WriteLine($"Department: {department.Name}"); foreach (var employee in department.Employees) { Console.WriteLine($"Employee: {employee.FullName}, ID: {employee.EmployeeID}"); } } }
XML to object conversion in C#:
Converting XML data to a custom object using XmlSerializer
.
using System; using System.IO; using System.Xml.Serialization; [Serializable] public class Order { public int OrderID { get; set; } public string Product { get; set; } public int Quantity { get; set; } } class Program { static void Main() { string xmlData = "<Order><OrderID>1001</OrderID><Product>Laptop</Product><Quantity>2</Quantity></Order>"; Order order; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(Order)); order = (Order)serializer.Deserialize(reader); } Console.WriteLine($"Order ID: {order.OrderID}, Product: {order.Product}, Quantity: {order.Quantity}"); } }
C# deserialize XML with namespaces:
Deserializing XML data containing namespaces using XmlSerializer
.
using System; using System.IO; using System.Xml.Serialization; [Serializable] [XmlRoot(Namespace = "http://example.com/namespace")] public class Document { public string Title { get; set; } } class Program { static void Main() { string xmlData = "<Document xmlns='http://example.com/namespace'><Title>Sample Document</Title></Document>"; Document document; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(Document)); document = (Document)serializer.Deserialize(reader); } Console.WriteLine($"Document Title: {document.Title}"); } }
XML array deserialization in C#: Deserializing an array of elements from XML data.
using System; using System.IO; using System.Xml.Serialization; [Serializable] [XmlRoot("Products")] public class ProductList { [XmlElement("Product")] public Product[] Products { get; set; } } [Serializable] public class Product { public string Name { get; set; } public double Price { get; set; } } class Program { static void Main() { string xmlData = "<Products><Product><Name>Laptop</Name><Price>999.99</Price></Product><Product><Name>Phone</Name><Price>299.99</Price></Product></Products>"; ProductList productList; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(ProductList)); productList = (ProductList)serializer.Deserialize(reader); } Console.WriteLine("Product List:"); foreach (var product in productList.Products) { Console.WriteLine($"Name: {product.Name}, Price: ${product.Price}"); } } }
Deserializing XML to generic list in C#: Deserializing XML content to a generic list of objects.
using System; using System.Collections.Generic; using System.IO; using System.Xml.Serialization; [Serializable] public class Student { public int ID { get; set; } public string Name { get; set; } public double GPA { get; set; } } class Program { static void Main() { string xmlData = "<Students><Student><ID>101</ID><Name>John Doe</Name><GPA>3.5</GPA></Student><Student><ID>102</ID><Name>Jane Smith</Name><GPA>3.8</GPA></Student></Students>"; List<Student> studentList; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(List<Student>), new XmlRootAttribute("Students")); studentList = (List<Student>)serializer.Deserialize(reader); } Console.WriteLine("Student List:"); foreach (var student in studentList) { Console.WriteLine($"ID: {student.ID}, Name: {student.Name}, GPA: {student.GPA}"); } } }
Custom XML deserialization in C#: Implementing custom logic during XML deserialization.
using System; using System.IO; using System.Xml; using System.Xml.Serialization; [Serializable] public class Person { [XmlElement("Name")] public string Name { get; set; } [XmlElement("BirthDate")] public DateTime BirthDate { get; set; } // Custom deserialization logic [XmlIgnore] public int Age { get; set; } [XmlElement("Age")] public string AgeString { get { return Age.ToString(); } set { Age = int.Parse(value); } } } class Program { static void Main() { string xmlData = "<Person><Name>John Doe</Name><BirthDate>1990-01-01</BirthDate><Age>32</Age></Person>"; Person person; using (StringReader reader = new StringReader(xmlData)) { XmlSerializer serializer = new XmlSerializer(typeof(Person)); person = (Person)serializer.Deserialize(reader); } Console.WriteLine($"Name: {person.Name}, BirthDate: {person.BirthDate.ToShortDateString()}, Age: {person.Age}"); } }