Vince Lee
Vince Lee

Reputation: 89

c# XML serialisation of child class - remove xmlns:p1 and p1:type attributes from root node

Using the bog-standard System.Xml.Serialization.XmlSerializer, I am serializing an object who's class inherits from another. Inspecting the resulting XML, the root node is being given the attributes "p1:type" and "xmlns:p1":

<ApiSubmission ApiVersion="1" CustId="100104" p1:type="OrderConfirmationApiSubmission" 
    xmlns:p1="http://www.w3.org/2001/XMLSchema-instance">
    ...
</ApiSubmission>

Is there a nice way to remove these attributes?

Upvotes: 2

Views: 1305

Answers (1)

mitchellJ
mitchellJ

Reputation: 734

So I came upon this same issue ~5 years after this question was originally asked and was disappointed that no one had answered. After searching around I cobbled something together that allows me to strip out the type attribute in a derived class.

    internal static string SerializeObject(object objectToSerialize, bool OmitXmlDeclaration = true, System.Type type = null, bool OmitType = false, bool RemoveAllNamespaces = true)
    {
        XmlSerializer x;
        string output;

        if (type != null)
        {
            x = new XmlSerializer(type);
        }
        else
        {
            x = new XmlSerializer(objectToSerialize.GetType());
        }

        XmlWriterSettings settings = new XmlWriterSettings() { Indent = false, OmitXmlDeclaration = OmitXmlDeclaration, NamespaceHandling = NamespaceHandling.OmitDuplicates };

        using (StringWriter swriter = new StringWriter())
        using (XmlWriter xmlwriter = XmlWriter.Create(swriter, settings))
        {
            x.Serialize(xmlwriter, objectToSerialize);

            output = swriter.ToString();
        }

        if (RemoveAllNamespaces || OmitType)
        {
            XDocument doc = XDocument.Parse(output);

            if (RemoveAllNamespaces)
            {
                foreach (var element in doc.Root.DescendantsAndSelf())
                {
                    element.Name = element.Name.LocalName;
                    element.ReplaceAttributes(GetAttributesWithoutNamespace(element));
                }
            }

            if (OmitType)
            {
                foreach (var node in doc.Descendants().Where(e => e.Attribute("type") != null))
                {
                    node.Attribute("type").Remove();
                }
            }

            output = doc.ToString();
        }

        return output;
    }

I use this and [XmlInclude] the derived class in the base class. Then OmitType and RemoveAllNamespaces. Essentially the derived class is then treated as if it were the base class.

Upvotes: 1

Related Questions