繁体   English   中英

C#序列化程序未向根元素添加前缀

[英]C# serializer not adding prefix to root element

看到很多人都遇到同样的问题,却在任何地方都没有答案,所以我自己在这里回答;

序列化应附加前缀的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>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM