Skip to main content

XML helper class to serialize an object and generate an XML string without the XML declaration and namespace.

// -----------------------------------------------------------------------
// Program.cs
// -----------------------------------------------------------------------

using XmlHelper.Console;

var invoice1 = new Invoice("Goods", Guid.NewGuid(), 8749392773);
var invoice2 = new Invoice("Services", Guid.NewGuid(), 2827387193);

var body = new Body();
body.AddInvoice(invoice1);
body.AddInvoice(invoice2);

var message = new Message(body);
var xmlBody = message.ToXml();
Console.WriteLine(xmlBody);
// <message>
//   <body>
//     <invoices>
//       <invoice eventId="e9819de8-2220-4c70-b228-b2e4a3522a0e" number="8749392773">
//         <name>Goods</name>
//       </invoice>
//       <invoice eventId="9275f21f-a330-4105-8467-a6216a9a0b14" number="2827387193">
//         <name>Services</name>
//       </invoice>
//     </invoices>
//   </body>
// </message>

Console.ReadKey();

// -----------------------------------------------------------------------
// XmlHelper.cs
// -----------------------------------------------------------------------

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

namespace XmlHelper.Console;

public static class XmlHelper
{
    /// <summary>
    /// XML string without declaration and namespace.
    /// </summary>
    /// <param name="obj">The object to serialize to XML.</param>
    /// <typeparam name="T">The object's type.</typeparam>
    /// <returns>The object as an XML string.</returns>
    /// <exception cref="ArgumentNullException">Thrown if <see cref="obj"/> is null.</exception>
    /// <remarks>
    /// https://learn.microsoft.com/en-us/answers/questions/205709/c-xml-without-declaration-and-namespace
    /// https://dotnetfiddle.net/m8OqE0
    /// </remarks>
    public static string ToXml<T>(this T obj)
    {
        if (obj == null)
        {
            throw new ArgumentNullException(nameof(obj));
        }

        // Remove Declaration
        var settings = new XmlWriterSettings
        {
            Indent = true, // set to false to remove indention and line breaks
            OmitXmlDeclaration = true // set to false to include "<?xml version="1.0" encoding="utf-16"?>"
        };

        // Remove Namespace
        var ns = new XmlSerializerNamespaces(new XmlQualifiedName[] { XmlQualifiedName.Empty });

        using (var stream = new StringWriter())
        {
            using (var writer = XmlWriter.Create(stream, settings))
            {
                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(writer, obj, ns);

                return stream.ToString();
            }
        }
    }
}

// -----------------------------------------------------------------------
// Classes.cs
// -----------------------------------------------------------------------

using System.Xml.Serialization;

namespace XmlHelper.Console;

[XmlType("invoice")]
public class Invoice
{
    public Invoice()
    {
        Name = string.Empty;
        EventId = Guid.Empty;
    }

    public Invoice(string name)
    {
        Name = name;
        EventId = Guid.NewGuid();
    }

    public Invoice(string name, Guid eventId, long number)
    {
        Name = name;
        EventId = eventId;
        Number = number;
    }

    [XmlAttribute("eventId")]
    public Guid EventId { get; set; }

    [XmlAttribute("number")]
    public long Number { get; set; }

    [XmlElement("name")]
    public string Name { get; set; }
}

public class Body
{
    public Body()
    {
        Invoices = new List<Invoice>();
    }

    [XmlArray("invoices")]
    public List<Invoice> Invoices { get; }

    public void AddInvoice(Invoice invoice)
    {
        Invoices.Add(invoice);
    }
}

[XmlType("message")]
public class Message
{
    public Message()
    {
        Body = new Body();
    }

    public Message(Body body)
    {
        Body = body;
    }

    [XmlElement("body")]
    public Body Body { get; set; }
}