c#子类的XML序列化 - 从根节点中删除xmlns:p1和p1:type属性

时间:2014-11-27 11:16:48

标签: c# xml serialization

使用bog标准的System.Xml.Serialization.XmlSerializer,我正在序列化一个类继承自另一个的对象。检查生成的XML,根节点被赋予属性“p1:type”和“xmlns:p1”:

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

有没有一种很好的方法来删除这些属性?

1 个答案:

答案 0 :(得分:0)

因此,在最初提出这个问题的5年后,我遇到了同样的问题,对没有人回答感到失望。搜索后,我将一些东西拼凑在一起,使我可以在派生类中删除type属性。

    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;
    }

我使用它,并在基类中使用[XmlInclude]派生类。然后是OmitType和RemoveAllNamespaces。本质上,然后将派生类视为基类。