Serializing WITHOUT xmlns

前端 未结 4 1836
野性不改
野性不改 2020-12-17 10:30

I have a couple extension methods that handle serialization of my classes, and since it can be a time consuming process, they are created once per class, and handed out by t

4条回答
  •  抹茶落季
    2020-12-17 11:00

     public static byte[] SerializeByteByType(object objectToSerialize, Type type)
        {
            XmlWriterSettings xmlSetting = new XmlWriterSettings()
            {
                NewLineOnAttributes = false,
                OmitXmlDeclaration = true,
                Indent = false,
                NewLineHandling = NewLineHandling.None,
                Encoding = Encoding.UTF8,
                NamespaceHandling = NamespaceHandling.OmitDuplicates
            };
    
            using (MemoryStream stm = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(stm, xmlSetting))
                {
                    var xmlAttributes = new XmlAttributes();
                    var xmlAttributeOverrides = new XmlAttributeOverrides();
    
                    xmlAttributes.Xmlns = false;
                    xmlAttributes.XmlType = new XmlTypeAttribute() { Namespace = "" };
                    xmlAttributeOverrides.Add(type, xmlAttributes);
    
                    XmlSerializer serializer = new XmlSerializer(type, xmlAttributeOverrides);
                    //Use the following to serialize without namespaces
                    XmlSerializerNamespaces xmlSrzNamespace = new XmlSerializerNamespaces();
                    xmlSrzNamespace.Add("", "");
    
                    serializer.Serialize(writer, objectToSerialize, xmlSrzNamespace);
                    stm.Flush();
                    stm.Position = 0;
                }
    
                return stm.ToArray();
            }
        }         
    

提交回复
热议问题