XDocument Serialize

In this chapter you will learn:

  1. How to Serialize an XDocument

Serialize an XDocument

Serialize an XDocument to a string with the XML declaration.

using System;// j av a2s  .c om
using System.Text;
using System.Xml;

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        var doc = new XDocument(
                new XDeclaration("1.0", "utf-8", "yes"),
                new XElement("test", "data")
                );
        var output = new StringBuilder();
        var settings = new XmlWriterSettings { Indent = true };
        using (XmlWriter xw = XmlWriter.Create(output, settings))
            doc.Save(xw);

        Console.WriteLine(output.ToString());
    }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. Create XElement with namespace
Home » C# Tutorial » XML Linq
XDocument
Create XDocument
Add to XDocument
Parse XML file with XDocument
Load XML string with XDocument
XDocument Root
Query XML document with Linq
Save XML document
XDocument Serialize
XElement namespace
Adding attribute
XElement's NextNode
XAttribute
XAttribute value
XAttribute Properties
XAttribute namespace
XComment
XDeclaration
XML declaration
XCData
XNamespace