Multiple Approaches to XML Generation in C#: From Object Mapping to Stream Processing

Nov 21, 2025 · Programming · 12 views · 7.8

Keywords: C# | XML Generation | XmlSerializer | XDocument | XmlWriter

Abstract: This article provides an in-depth exploration of four primary methods for generating XML documents in C#: XmlSerializer, XDocument, XmlDocument, and XmlWriter. Through detailed code examples and performance analysis, it compares the applicable scenarios, advantages, and implementation details of each approach, helping developers choose the most suitable XML generation solution based on specific requirements.

Overview of XML Generation Methods

Generating valid XML documents is a common requirement in C# development. Depending on different application scenarios and performance requirements, developers can choose from multiple methods to achieve XML generation. This article details four primary XML generation approaches and demonstrates their implementations through practical code examples.

XmlSerializer Approach

XmlSerializer provides an object model-based XML serialization approach, particularly suitable for directly mapping .NET objects to XML structures. The main advantage of this method lies in its declarative programming model, where developers can define XML structures simply through attribute annotations.

[Serializable]
public class Foo
{
    [XmlAttribute]
    public string Bar { get; set; }
    public string Nested { get; set; }
}

// Usage example
Foo foo = new Foo
{
    Bar = "some & value",
    Nested = "data"
};
new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);

The XML output generated by XmlSerializer is as follows:

<Foo Bar="some &amp; value">
  <Nested>data</Nested>
</Foo>

It's important to note that XmlSerializer requires all serialized properties to have public getter and setter methods. For immutable types, implementing the IXmlSerializable interface is necessary, but this reduces the convenience of using XmlSerializer.

XDocument Approach

XDocument is the core class of LINQ to XML, providing a powerful and intuitive way to construct XML documents. Through functional construction patterns, developers can create complex XML document structures in a declarative manner.

// Basic construction example
Console.WriteLine(
    new XElement("Foo",
        new XAttribute("Bar", "some & value"),
        new XElement("Nested", "data")));

The XElement constructor supports flexible content parameter passing:

// Complex structure example
XElement contacts = new XElement("Contacts",
    new XElement("Contact",
        new XElement("Name", "Patrick Hines"),
        new XElement("Phone", "206-555-0144"),
        new XElement("Address",
            new XElement("Street1", "123 Main St"),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042")
        )
    )
);

XmlDocument Approach

XmlDocument is the traditional DOM (Document Object Model) implementation, providing comprehensive XML document manipulation capabilities. While it may be less intuitive than XDocument in some scenarios, it remains valuable in situations requiring full DOM functionality.

XmlDocument doc = new XmlDocument();
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));
el.SetAttribute("Bar", "some & value");
el.AppendChild(doc.CreateElement("Nested")).InnerText = "data";
Console.WriteLine(doc.OuterXml);

XmlWriter Approach

For scenarios requiring large XML document processing or high performance, XmlWriter provides a stream-based writing approach. Although this method offers a lower-level programming model, it has significant advantages in memory usage and performance.

XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data");
writer.WriteEndElement();
writer.Close();

XmlWriter is particularly suitable for processing large data streams, such as generating XML documents from CSV files. Since it employs stream processing and doesn't load the entire document into memory, it can efficiently handle XML files of hundreds of MB or larger.

Performance and Applicable Scenario Analysis

Different XML generation methods exhibit significant differences in performance and applicable scenarios:

When choosing an XML generation method, developers need to comprehensively consider factors such as document size, performance requirements, development efficiency, and functional needs. For most application scenarios, XDocument provides the best balance, while XmlWriter is the better choice in performance-critical situations.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.