Converting XDocument to Objects in C#
Converting XDocument to objects is a common requirement when working with XML in C#. This process, often referred to as deserialization, involves reading the XML document and mapping its elements and attributes to the properties of an object. This article will guide you through this process using simple examples.
Introduction to XDocument
XDocument is part of the LINQ to XML library in .NET, which provides easy-to-use methods for querying and manipulating XML data. Before you convert an XDocument to an object, you must understand the structure of your XML and how it relates to the object model you are targeting.
Basic Deserialization
To deserialize an XML document to an object, you will typically define a class that represents the XML structure and use LINQ to query the XDocument and populate the object.
Example: Deserialize a Simple XML to an Object
Assuming you have an XML file representing a book:
<Book>
<Title>Introduction to C#</Title>
<Author>Jon Doe</Author>
<Price>29.99</Price>
</Book>
You would first define a C# class that matches this XML structure:
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
Then, you can deserialize the XDocument to this Book object using LINQ:
XDocument doc = XDocument.Load("path_to_xml.xml");
var bookQuery = from b in doc.Descendants("Book")
select new Book
{
Title = b.Element("Title").Value,
Author = b.Element("Author").Value,
Price = Convert.ToDecimal(b.Element("Price").Value)
};
Book myBook = bookQuery.SingleOrDefault();
Handling Complex XML Structures
For more complex XML documents with nested elements or attributes, your class structures will need to reflect this complexity, and your LINQ queries may become more involved.
Example: Deserialize Complex XML
Consider an XML with nested elements:
<Library>
<Book>
<Title>Advanced C#</Title>
<Author>Jane Doe</Author>
<Price>49.99</Price>
</Book>
<Book>
<Title>Learning LINQ</Title>
<Author>John Smith</Author>
<Price>34.99</Price>
</Book>
</Library>
You would need a Library class containing a list of Book objects:
public class Library
{
public List<Book> Books { get; set; }
}
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
Then, deserialize the XML to the Library object:
XDocument doc = XDocument.Load("path_to_xml.xml");
Library library = new Library
{
Books = (from b in doc.Descendants("Book")
select new Book
{
Title = b.Element("Title").Value,
Author = b.Element("Author").Value,
Price = Convert.ToDecimal(b.Element("Price").Value)
}).ToList()
};
Conclusion
Converting XDocument to objects in C# is a versatile technique for processing XML data. By properly defining your object models and utilizing LINQ queries, you can efficiently transform XML documents into C# objects, making them easier to work with in your applications.