1

我有一个包含 .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 .....

我越来越 ?

4

1 回答 1

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>
于 2013-06-03T14:08:58.497 回答