C# 序列化程序未向根元素添加前缀 [英] C# serializer not adding prefix to root element

查看:53
本文介绍了C# 序列化程序未向根元素添加前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

在序列化应附加前缀的 XML 类时,前缀丢失.

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");

这是我的序列化方法;

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>

缺少前缀,它应该看起来像这样..

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>

推荐答案

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

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

这篇关于C# 序列化程序未向根元素添加前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆