In this article [Show more]
C# XML Parser
Parsing XML in C# is a fundamental skill for developers working with various data formats and services. This article explores how to parse XML documents in C# using different approaches and the .NET Framework's capabilities.
Using XmlDocument for XML Parsing
The XmlDocument class is a part of the System.Xml namespace and provides a robust set of features for navigating and parsing XML data.
Example: Parsing XML with XmlDocument
using System;
using System.Xml;
public class XmlParsingExample
{
public static void Main()
{
// XML string to be parsed
string xmlString = @"
<books>
<book>
<title>1984</title>
<author>George Orwell</author>
<year>1949</year>
</book>
<book>
<title>Brave New World</title>
<author>Aldous Huxley</author>
<year>1932</year>
</book>
</books>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xmlString);
// Get all book nodes
XmlNodeList bookNodes = xmlDoc.GetElementsByTagName("book");
Console.WriteLine("Books found:");
foreach (XmlNode book in bookNodes)
{
string title = book["title"].InnerText;
string author = book["author"].InnerText;
string year = book["year"].InnerText;
Console.WriteLine($"Title: {title}, Author: {author}, Year: {year}");
}
}
}
Tips for Using XmlDocument
- Load Methods: Use Load to parse from files and LoadXml from strings.
- Node Selection: Use methods like GetElementsByTagName to navigate through elements.
Using XDocument for LINQ-based Parsing
XDocument is part of LINQ to XML, providing a more modern and intuitive way to parse XML by integrating directly with LINQ.
Example: Parsing XML with XDocument
using System;
using System.Linq;
using System.Xml.Linq;
public class LinqXmlParsingExample
{
public static void Main()
{
string xmlString = @"
<books>
<book>
<title>The Great Gatsby</title>
<author>F. Scott Fitzgerald</author>
<year>1925</year>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<year>1960</year>
</book>
</books>";
XDocument xDoc = XDocument.Parse(xmlString);
var books = from book in xDoc.Descendants("book")
select new
{
Title = book.Element("title")?.Value,
Author = book.Element("author")?.Value,
Year = book.Element("year")?.Value
};
Console.WriteLine("Books found:");
foreach (var book in books)
{
Console.WriteLine($"Title: {book.Title}, Author: {book.Author}, Year: {book.Year}");
}
}
}
Tips for Using XDocument
- LINQ Integration: Use LINQ queries to easily filter and select data from XML.
- Element Access: Directly access elements and their values using .Element and .Value.
Conclusion
C# provides powerful tools for XML parsing, each suited to different scenarios and preferences. Whether you prefer the traditional DOM approach with XmlDocument or the LINQ-integrated XDocument, both offer efficient ways to work with XML data in your applications.