Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change number of characters used for indentation when writing XML with XDocument

I am trying to change the default indentation of XDocument from 2 to 3, but I'm not quite sure how to proceed. How can this be done?

I'm familiar with XmlTextWriter and have used code as such:

using System.Xml;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string destinationFile = "C:\myPath\results.xml";
            XmlTextWriter writer = new XmlTextWriter(destinationFile, null);
            writer.Indentation = 3;
            writer.WriteStartDocument();

            // Add elements, etc

            writer.WriteEndDocument();
            writer.Close();
        }
    }
}

For another project I used XDocument because it works better for my implementation similar to this:

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

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Source file has indentation of 3
            string sourceFile = @"C:\myPath\source.xml";
            string destinationFile = @"C:\myPath\results.xml";

            List<XElement> devices = new List<XElement>();

            XDocument template = XDocument.Load(sourceFile);        

            // Add elements, etc

            template.Save(destinationFile);
        }
    }
}
like image 518
jmstoker Avatar asked Aug 29 '13 00:08

jmstoker


1 Answers

As @John Saunders and @sa_ddam213 noted, new XmlWriter is deprecated so I dug a little deeper and learned how to change indentation using XmlWriterSettings. The using statement idea I got from @sa_ddam213.

I replaced template.Save(destinationFile); with the following:

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "   ";  // Indent 3 Spaces

using (XmlWriter writer = XmlTextWriter.Create(destinationFile, settings))
{                    
    template.Save(writer);
}

This gave me the 3 space indentation that I needed. If more spaces are needed, just add them to IndentChars or "\t" can be used for tab.

like image 148
jmstoker Avatar answered Oct 15 '22 09:10

jmstoker