Skip to content

How to save XDocument to xml and use single quotes for attribute values

I had to do this for AVBlocks xml licenses recently. It is not straightforward, but here is the C# code.

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

namespace Primo.LicenseBuilder.Xml
{
    public static class XmlExtensions
    {
        public static string ToSingleQuoteString(this XDocument xDocument, 
                                                    System.Xml.Formatting formatting = Formatting.Indented)
        {
            using (StringWriter sw = new StringWriter())
            {
                using (XmlTextWriter writer = new XmlTextWriter(sw))
                {
                    writer.Formatting = formatting;
                    writer.QuoteChar = '\'';
                    writer.WriteNode(xDocument.CreateNavigator(), false);
                    writer.Flush();
                }

                return sw.ToString();
            }
        }
    }
}