当我无法控制序列化的.NET类型时,我可以为根元素添加前缀吗?

时间:2013-06-03 13:37:04

标签: c# .net xml serialization

我有一个包含.NET类型的库。该库有自己的配置(注释等),用于将类型序列化为XML,我没有源代码。

无论我做什么,我都无法添加我想要添加到输出XML的根元素的前缀。使用XmlSerializerNamespaces没有任何区别。这是一个显示我的代码的片段:

                    var comp = row[0] as LibraryType;
                    var ser = new XmlSerializer(comp.GetType());                                                                        
                    var strWriter = new StringWriter();
                    var xmlWriter = XmlWriter.Create(strWriter);
                    ser.Serialize(xmlWriter, comp);
                    string serXml = strWriter.ToString();

配置XMLSerializer是否有办法为root创建xlm输出,例如

<lt:LibraryType ....

而不是当前的

<LibraryType .....

我来了?

1 个答案:

答案 0 :(得分:2)

让我们说您的库类型看起来像

public class Foo
{
    public int i { get; set; }
}

public class Bar
{
    public Foo Foo { get; set; }
}

然后序列化应该看起来像

var comp = new Bar {Foo = new Foo()};

var overrides = new XmlAttributeOverrides();
overrides.Add(typeof (Bar), new XmlAttributes {XmlRoot = new XmlRootAttribute {Namespace = "http://tempuri.org"}});

// in case you want to remove prefix from members
var emptyNsAttribute = new XmlAttributes();
emptyNsAttribute.XmlElements.Add(new XmlElementAttribute { Namespace = "" });
overrides.Add(typeof(Bar), "Foo", emptyNsAttribute);
// if you actual library type contains more members, then you have to list all of them


var ser = new XmlSerializer(comp.GetType(), overrides);
var strWriter = new StringWriter();
var xmlWriter = XmlWriter.Create(strWriter);

var ns = new XmlSerializerNamespaces();
ns.Add("lt", "http://tempuri.org");
ser.Serialize(xmlWriter, comp, ns);
string serXml = strWriter.ToString();

,输出将是

<?xml version="1.0" encoding="utf-16"?><lt:Bar xmlns:lt="http://tempuri.org"><Foo><i>0</i></Foo></lt:Bar>