C# XML without declaration and namespace

Markus Freitag 3,791 Reputation points
2020-12-21T10:47:21.787+00:00

Hello,
Is there an easy way to get the XML without declaration and namespace? If yes, how?

public static class XMLHelper  
     {  
         public static string ToXML<T>(this T obj)  
         {  
             using (var stringwriter = new System.IO.StringWriter())  
             {  
                 var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));  
                 serializer.Serialize(stringwriter, obj);  
                 return stringwriter.ToString();  
             }  
         }  
     }  

49840-withoutdeclaration-namespace.png

Developer technologies C#
{count} votes

Accepted answer
  1. Yaz SHADMEHR 786 Reputation points
    2020-12-22T20:15:21.15+00:00

    @Markus Freitag To override the behaviour of XmlSerializer you need XmlWriterSettings for override or remove XML declaration and XmlSerializerNamespaces for override namespace:

    public static string ToXML<T>(this T obj)  
    {  
     // Remove Declaration  
     var settings = new XmlWriterSettings  
            {  
                 Indent = true,  
                 OmitXmlDeclaration = true  
            };  
      
     // Remove Namespace  
        var ns = new XmlSerializerNamespaces(new[] { 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();  
        }  
    }  
    

    See full example here.

    3 people found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Timon Yang-MSFT 9,606 Reputation points
    2020-12-22T09:04:19.943+00:00

    You can manually add an empty namespace to avoid adding those default namespaces:

        class Program  
        {  
            static void Main(string[] args)  
            {  
                XmlWriterSettings settings = new XmlWriterSettings();  
                settings.OmitXmlDeclaration = true;  
                using (XmlWriter writer = XmlWriter.Create("d:\\my.xml", settings))  
                {  
                    XmlSerializer ser = new XmlSerializer(typeof(Foo));  
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();  
                    ns.Add("", "");  
                    Foo foo = new Foo();  
                    foo.Bar = "abc";  
                    ser.Serialize(writer, foo, ns);  
                }  
            }  
        }  
      
        public class Foo  
        {  
            public string Bar { get;  set; }  
        }  
    

    50372-2.png


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Yitzhak Khabinsky 26,586 Reputation points
    2020-12-21T14:21:05.317+00:00

    The most natural and easy way to implement it is via XSLT.
    Please find below an example of it.

    The XSLT is generic. It will remove (1) XML prolog declaration, and (2) any namespace(s) from any XML file.

    Input XML

    <?xml version="1.0"?>
    <AMOUNT_MONEY xmlns="http://www.somewhere.com/ABC" version="5.252">
       <CURRENT_ADDRESS occupancy_status="RENT" occupancy_description="">
          <FORMER_ADDRESS street_address_1="1234 CIRCLE LN" county=""/>
       </CURRENT_ADDRESS>
    </AMOUNT_MONEY>
    

    XSLT

    <?xml version="1.0"?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>
    
     <xsl:template match="/|comment()|processing-instruction()">
     <xsl:copy>
     <xsl:apply-templates/>
     </xsl:copy>
     </xsl:template>
    
     <xsl:template match="*">
     <xsl:element name="{local-name()}">
     <xsl:apply-templates select="@*|node()"/>
     </xsl:element>
     </xsl:template>
    
     <xsl:template match="@*">
     <xsl:attribute name="{local-name()}">
     <xsl:value-of select="."/>
     </xsl:attribute>
     </xsl:template>
    </xsl:stylesheet>
    

    Output XML

    <AMOUNT_MONEY version="5.252">
     <CURRENT_ADDRESS occupancy_status="RENT" occupancy_description="">
     <FORMER_ADDRESS street_address_1="1234 CIRCLE LN" county="" />
     </CURRENT_ADDRESS>
    </AMOUNT_MONEY>
    

    c# to launch XSLT transformation

    void Main()
    {
       const string SOURCEXMLFILE = @"e:\Temp\UniversalShipment.xml";
       const string XSLTFILE = @"e:\Temp\RemoveNamespaces.xslt";
       const string OUTPUTXMLFILE = @"e:\temp\UniversalShipment_output.xml";
    
       try
       {
          XsltArgumentList xslArg = new XsltArgumentList();
    
          using (XmlReader src = XmlReader.Create(SOURCEXMLFILE))
          {
             XslCompiledTransform xslt = new XslCompiledTransform();
             xslt.Load(XSLTFILE, new XsltSettings(true, true), new XmlUrlResolver());
    
             XmlWriterSettings settings = xslt.OutputSettings.Clone();
             settings.IndentChars = "\t";
             // to remove BOM
             settings.Encoding = new UTF8Encoding(false);
    
             using (XmlWriter result = XmlWriter.Create(OUTPUTXMLFILE, settings))
             {
                xslt.Transform(src, xslArg, result, new XmlUrlResolver());
                result.Close();
             }
          }
          Console.WriteLine("File '{0}' has been generated.", OUTPUTXMLFILE);
       }
       catch (Exception ex)
       {
          Console.WriteLine(ex.Message);
       }
    }
    
    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.