序列化没有xmlns

时间:2010-06-22 15:10:18

标签: c# xml-serialization namespaces

我有几个扩展方法来处理我的类的序列化,因为它可能是一个耗时的过程,它们每个类创建一次,并通过此方法分发。

public static XmlSerializer GetSerializerFor(Type typeOfT)
{
    if (!serializers.ContainsKey(typeOfT))
    {
        var xmlAttributes = new XmlAttributes();
        var xmlAttributeOverrides = new XmlAttributeOverrides();

        System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

        xmlAttributes.Xmlns = false;
        xmlAttributeOverrides.Add(typeOfT, xmlAttributes);

        var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides);
        serializers.Add(typeOfT, newSerializer);
    }

    return serializers[typeOfT];
}

这是通过扩展方法.Serialize()

调用的
public static XElement Serialize(this object source)
{
    try
    {
        var serializer = XmlSerializerFactory.GetSerializerFor(source.GetType());
        var xdoc = new XDocument();
        using (var writer = xdoc.CreateWriter())
        {
            serializer.Serialize(writer, source, new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") }));
        }

        return (xdoc.Document != null) ? xdoc.Document.Root : new XElement("Error", "Document Missing");
    }
    catch (Exception x)
    {
        return new XElement("Error", x.ToString());
    }
}

不幸的是,在序列化自动生成的类时,它们会应用属性XmlTypeAttribute(Namespace="http://tempuri.org/")

这会导致非自动生成的对应项的反序列化失败。

我需要序列化程序完全忽略而不应用命名空间,但是我在第一段代码中编写的内容似乎没有删除它,我仍然最终得到像这样的xml

<Note>
  <ID xmlns="http://tempuri.org/">12</ID>
  <Author xmlns="http://tempuri.org/">
    <ID>1234</ID>
    <Type>Associate</Type>
    <IsAvailable>false</IsAvailable>
  </Author>
  <Created xmlns="http://tempuri.org/">2010-06-22T09:38:01.5024351-05:00</Created>
  <Text xmlns="http://tempuri.org/">This is an update</Text>
</Note>

而不是相同,减去xmlns="http://tempuri.org/"属性。

请帮助,谢谢,这让我发疯了!

编辑:

我知道问题,而不是如何修复它。

我的班级,不仅仅是简单的类型。

它包含具有其他类类型的属性。哪些也是使用XmlTypeAttribute(Namespace = "http://tempuri.org/")属性自动生成的。所以正在发生的事情是,当序列化发生时,它序列化我的类的属性,它们不会通过我的自定义序列化,因此,应用了属性而不是覆盖。

现在我只需要弄清楚如何跳过那个篮圈。有关如何的任何想法?

编辑2:

以下工作序列化WITHOUT xmlns ...但我在反序列化结束时遇到问题,只是还不确定它是否相关

public static XmlSerializer GetSerializerFor(Type typeOfT)
{
    if (!serializers.ContainsKey(typeOfT))
    {
        var xmlAttributes = new XmlAttributes();
        var xmlAttributeOverrides = new XmlAttributeOverrides();

        System.Diagnostics.Debug.WriteLine(string.Format("XmlSerializerFactory.GetSerializerFor(typeof({0}));", typeOfT));

        xmlAttributes.XmlType = new XmlTypeAttribute
        {
            Namespace = ""
        };

        xmlAttributes.Xmlns = false;

        var types = new List<Type> {typeOfT, typeOfT.BaseType};

        foreach (var property in typeOfT.GetProperties())
        {
            types.Add(property.PropertyType);
        }

        types.RemoveAll(t => t.ToString().StartsWith("System."));

        foreach (var type in types)
        {
            xmlAttributeOverrides.Add(type, xmlAttributes);
        }

        var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides);
        //var newSerializer = new XmlSerializer(typeOfT, xmlAttributeOverrides, extraTypes.ToArray(), new XmlRootAttribute(), string.Empty);
        //var newSerializer = new XmlSerializer(typeOfT, string.Empty);

        serializers.Add(typeOfT, newSerializer);
    }

    return serializers[typeOfT];
}

EDIT3: 结束使用解决方案 How to remove all namespaces from XML with C#?

public static XElement RemoveAllNamespaces(this XElement source)
{
    return !source.HasElements
               ? new XElement(source.Name.LocalName)
                     {
                         Value = source.Value
                     }
               : new XElement(source.Name.LocalName, source.Elements().Select(el => RemoveAllNamespaces(el)));
}

4 个答案:

答案 0 :(得分:48)

一个有效的解决方案,用于记录!

var ns = new XmlSerializerNamespaces();
ns.Add("", ""); 
var serializer = new XmlSerializer(yourType); 
serializer.Serialize(xmlTextWriter, someObject, ns);

答案 1 :(得分:3)

没问题 - 只需将空字符串作为默认名称空间传递给XML序列化程序:

XmlSerializer newSerializer = 
   new XmlSerializer(typeOfT, "");

不幸的是,如果你真的需要定义XmlAttributeOverrides和默认命名空间,那么没有简单的构造函数重载 - 所以你可以跳过XmlAttributeOverrides并使用我提到的那个构造函数,或者你需要使用定义所有可能参数的那个(包括XmlAttributeOverrides和默认的XML命名空间 - 以及更多)。

答案 2 :(得分:1)

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

答案 3 :(得分:0)

    public static string SerializeToXml(object obj)
    {
        UTF8Encoding encoding = new UTF8Encoding(false);

        var xmlAttributes = new XmlAttributes();
        xmlAttributes.Xmlns = false;
        xmlAttributes.XmlType = new XmlTypeAttribute() { Namespace = "" };

        var xmlAttributeOverrides = new XmlAttributeOverrides();

        var types = obj.GetType().Assembly.GetTypes().Where(t => string.Equals(t.Namespace, obj.GetType().Namespace, StringComparison.Ordinal));
        foreach (var t in types) xmlAttributeOverrides.Add(t, xmlAttributes);

        XmlSerializer sr = new XmlSerializer(obj.GetType(), xmlAttributeOverrides);

        MemoryStream memoryStream = new MemoryStream();
        StreamWriter writer = new StreamWriter(memoryStream, encoding);

        XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
        namespaces.Add(string.Empty, string.Empty);

        // get the stream from the writer
        memoryStream = writer.BaseStream as MemoryStream;

        sr.Serialize(writer, obj, namespaces);

        // apply encoding to the stream 
        return (encoding.GetString(memoryStream.ToArray()).Trim());
    }
  

它甚至适用于包含嵌套对象的复杂对象   归功于user3444796和Mentor