C# serializer not adding prefix to root element

我们两清 提交于 2019-12-08 09:03:57

问题


Seen lots of people with this same issue and no answers anywhere, so answering it myself here;

When serializing an XML class that should have a prefix attached to it, the prefix is missing.

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

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

And this is my serializing method;

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

This produces;

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

Which is missing the prefix, it should look like this..

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

回答1:


If your serializer includes an xmlrootattribute when it is created, it doesn't apply namespaces you have specified manually, and therefore misses the "isd" tag off the first element. The easiest fix is to remove the 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();
    }
}


来源:https://stackoverflow.com/questions/49556390/c-sharp-serializer-not-adding-prefix-to-root-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!