C#serializer没有为根元素添加前缀

时间:2018-03-29 12:42:25

标签: c# xml serializer

看到很多人有同样的问题而且没有任何答案,所以在这里自己回答;

序列化应附加前缀的XML类时,前缀缺失。

[XmlRoot(ElementName = "Preadvice", Namespace = "http://www.wibble.com/PreadviceRequest")]
public class Preadvice
{
}

var XMLNameSpaces = new XmlSerializerNamespaces();
XMLNameSpaces.Add("isd", "http://www.wibble.com/PreadviceRequest");

这是我的序列化方法;

public static string SerializeStandardObject<T>(T obj, XmlSerializerNamespaces ns, XmlAttributeOverrides xao, XmlRootAttribute xra)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T), (xao == null ? new XmlAttributeOverrides() : xao), new Type[] { obj.GetType() }, (xra == null ? new XmlRootAttribute(obj.GetType().Name) : xra), "");

    using (StringWriter sw = new StringWriter())
    {
        using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw))
        {
            serializer.Serialize(writer, obj, (ns == null ? new XmlSerializerNamespaces() : ns));
        }
        return sw.ToString();
    }
}

这会产生;

<?xml version="1.0" encoding="utf-16"?>
<Preadvice xmlns:isd="http://www.wibble.com/PreadviceRequest">
</Preadvice>

哪个缺少前缀,它应该是这样的..

<?xml version="1.0" encoding="utf-16"?>
<isd:Preadvice xmlns:isd="http://www.wibble.com/PreadviceRequest">
</isd:Preadvice>

1 个答案:

答案 0 :(得分:0)

如果序列化程序在创建时包含xmlrootattribute,则它不会应用您手动指定的名称空间,因此会错过第一个元素的“isd”标记。最简单的解决方法是删除xmlrootattribute;

public static string SerializeStandardObject<T>(T obj, XmlSerializerNamespaces ns)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (StringWriter sw = new StringWriter())
    {
        using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw))
        {
            serializer.Serialize(writer, obj, (ns == null ? new XmlSerializerNamespaces() : ns));
        }
        return sw.ToString();
    }
}