C# -

XML Handling

XML (eXtensible Markup Language) is a versatile format for structuring data. C# provides powerful libraries for parsing, generating, and manipulating XML data. This tutorial covers the basics, advanced concepts, and best practices for handling XML in C#.


1. Introduction to XML Handling

XML is widely used for data interchange and storage. C# provides several classes in the System.Xml namespace for working with XML data.

        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xml = "<Person><Name>John</Name><Age>30</Age></Person>";
        var doc = new XmlDocument();
        doc.LoadXml(xml);
        var name = doc.SelectSingleNode("/Person/Name").InnerText;
        var age = doc.SelectSingleNode("/Person/Age").InnerText;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    
        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xml = "<Person><Name>Jane</Name><Age>25</Age></Person>";
        var doc = XDocument.Parse(xml);
        var name = doc.Root.Element("Name").Value;
        var age = doc.Root.Element("Age").Value;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    

2. Reading XML Files

Reading XML files into C# objects is a fundamental operation. Here's how you can read an XML file using XmlDocument and XDocument.

        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XmlDocument();
        doc.Load("person.xml");
        var name = doc.SelectSingleNode("/Person/Name").InnerText;
        var age = doc.SelectSingleNode("/Person/Age").InnerText;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    
        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = XDocument.Load("person.xml");
        var name = doc.Root.Element("Name").Value;
        var age = doc.Root.Element("Age").Value;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    

3. Writing XML Files

Writing XML files from C# objects is equally important. Here's how you can generate an XML file.

        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XmlDocument();
        var root = doc.CreateElement("Person");
        var name = doc.CreateElement("Name");
        name.InnerText = "John";
        var age = doc.CreateElement("Age");
        age.InnerText = "30";
        root.AppendChild(name);
        root.AppendChild(age);
        doc.AppendChild(root);
        doc.Save("person.xml");
    }
}
        
    
        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XDocument(
            new XElement("Person",
                new XElement("Name", "Jane"),
                new XElement("Age", "25")
            )
        );
        doc.Save("person.xml");
    }
}
        
    

4. Parsing XML Strings

Parsing XML strings into C# objects is a common requirement. Here's how you can parse an XML string using XmlDocument and XDocument.

        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xmlString = "<Person><Name>John</Name><Age>30</Age></Person>";
        var doc = new XmlDocument();
        doc.LoadXml(xmlString);
        var name = doc.SelectSingleNode("/Person/Name").InnerText;
        var age = doc.SelectSingleNode("/Person/Age").InnerText;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    
        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xmlString = "<Person><Name>Jane</Name><Age>25</Age></Person>";
        var doc = XDocument.Parse(xmlString);
        var name = doc.Root.Element("Name").Value;
        var age = doc.Root.Element("Age").Value;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    

5. Creating XML Strings

Creating XML strings from C# objects can be useful for various purposes. Here's how you can convert an object to an XML string.

        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XmlDocument();
        var root = doc.CreateElement("Person");
        var name = doc.CreateElement("Name");
        name.InnerText = "John";
        var age = doc.CreateElement("Age");
        age.InnerText = "30";
        root.AppendChild(name);
        root.AppendChild(age);
        doc.AppendChild(root);
        var xmlString = doc.OuterXml;
        Console.WriteLine(xmlString);
    }
}
        
    
        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XDocument(
            new XElement("Person",
                new XElement("Name", "Jane"),
                new XElement("Age", "25")
            )
        );
        var xmlString = doc.ToString();
        Console.WriteLine(xmlString);
    }
}
        
    

6. Using XmlDocument

XmlDocument provides a way to work with XML documents using a DOM (Document Object Model) approach.

        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xmlString = "<Person><Name>John</Name><Age>30</Age></Person>";
        var doc = new XmlDocument();
        doc.LoadXml(xmlString);
        var root = doc.DocumentElement;
        var name = root.SelectSingleNode("Name").InnerText;
        var age = root.SelectSingleNode("Age").InnerText;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    
        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XmlDocument();
        var root = doc.CreateElement("Person");
        var name = doc.CreateElement("Name");
        name.InnerText = "Jane";
        var age = doc.CreateElement("Age");
        age.InnerText = "25";
        root.AppendChild(name);
        root.AppendChild(age);
        doc.AppendChild(root);
        doc.Save("person.xml");
    }
}
        
    

7. Using XDocument

XDocument is part of LINQ to XML and provides a more modern and flexible way to work with XML documents.

        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xmlString = "<Person><Name>John</Name><Age>30</Age></Person>";
        var doc = XDocument.Parse(xmlString);
        var name = doc.Root.Element("Name").Value;
        var age = doc.Root.Element("Age").Value;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    
        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XDocument(
            new XElement("Person",
                new XElement("Name", "Jane"),
                new XElement("Age", "25")
            )
        );
        doc.Save("person.xml");
    }
}
        
    

8. XML Serialization

XML serialization allows you to convert C# objects to XML format and vice versa. Here's how to serialize and deserialize objects.

        
            using System;
using System.IO;
using System.Xml.Serialization;

namespace XmlHandlingExamples;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        var person = new Person { Name = "John", Age = 30 };
        var serializer = new XmlSerializer(typeof(Person));
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, person);
            var xmlString = writer.ToString();
            Console.WriteLine(xmlString);
        }
    }
}
        
    
        
            using System;
using System.IO;
using System.Xml.Serialization;

namespace XmlHandlingExamples;

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public Address Address { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        var person = new Person
        {
            Name = "Jane",
            Age = 25,
            Address = new Address { Street = "123 Main St", City = "Springfield" }
        };
        var serializer = new XmlSerializer(typeof(Person));
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, person);
            var xmlString = writer.ToString();
            Console.WriteLine(xmlString);
        }
    }
}
        
    

9. Handling Namespaces in XML

Namespaces are used in XML to avoid element name conflicts. Here's how to handle namespaces in XML documents.

        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var ns = "http://example.com/person";
        var doc = new XDocument(
            new XElement(XName.Get("Person", ns),
                new XElement(XName.Get("Name", ns), "John"),
                new XElement(XName.Get("Age", ns), "30")
            )
        );
        doc.Save("person.xml");
    }
}
        
    
        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xmlString = "<Person xmlns='http://example.com/person'><Name>Jane</Name><Age>25</Age></Person>";
        var doc = new XmlDocument();
        doc.LoadXml(xmlString);
        var nsmgr = new XmlNamespaceManager(doc.NameTable);
        nsmgr.AddNamespace("p", "http://example.com/person");
        var name = doc.SelectSingleNode("/p:Person/p:Name", nsmgr).InnerText;
        var age = doc.SelectSingleNode("/p:Person/p:Age", nsmgr).InnerText;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    

10. Validating XML with XSD

XML Schema Definition (XSD) provides a way to define the structure and data types of an XML document. Here's how to validate XML against an XSD schema.

        
            using System;
using System.Xml;
using System.Xml.Schema;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XmlDocument();
        doc.Schemas.Add("http://example.com/person", "person.xsd");
        doc.Load("person.xml");
        doc.Validate((sender, e) => Console.WriteLine(e.Message));
    }
}
        
    
        
            using System;
using System.Xml.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = XDocument.Load("person.xml");
        var schemas = new XmlSchemaSet();
        schemas.Add("http://example.com/person", "person.xsd");
        doc.Validate(schemas, (sender, e) => Console.WriteLine(e.Message));
    }
}
        
    

11. Querying XML with XPath

XPath is a language for selecting nodes from an XML document. Here's how to use XPath to query XML documents.

        
            using System;
using System.Xml;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = new XmlDocument();
        doc.Load("person.xml");
        var name = doc.SelectSingleNode("/Person/Name").InnerText;
        var age = doc.SelectSingleNode("/Person/Age").InnerText;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    
        
            using System;
using System.Xml.Linq;
using System.Linq;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var doc = XDocument.Load("person.xml");
        var name = doc.Descendants("Name").First().Value;
        var age = doc.Descendants("Age").First().Value;
        Console.WriteLine($"Name: {name}, Age: {age}");
    }
}
        
    

12. Transforming XML with XSLT

XSLT (eXtensible Stylesheet Language Transformations) is used to transform XML documents into different formats. Here's how to use XSLT in C#.

        
            using System;
using System.Xml;
using System.Xml.Xsl;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xslt = new XslCompiledTransform();
        xslt.Load("transform.xslt");
        xslt.Transform("person.xml", "person.html");
    }
}
        
    
        
            using System;
using System.Xml.Linq;
using System.Xml.Xsl;

namespace XmlHandlingExamples;

public class Program
{
    public static void Main(string[] args)
    {
        var xslt = new XslCompiledTransform();
        xslt.Load("transform.xslt");
        xslt.Transform("person.xml", "person.html");
    }
}
        
    


13. Conclusion

XML handling in C# is a powerful capability that enables you to work with structured data effectively. By using the provided libraries and following best practices, you can efficiently parse, generate, and manipulate XML data in your applications.