当我无法控制序列化的.net类型时,我可以向根元素添加前缀吗?
本文关键字:可以向 我可以 元素 添加 加前缀 控制 序列化 类型 net | 更新日期: 2023-09-27 18:16:30
我有一个包含。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创建xml输出,例如
<lt:LibraryType ....
代替当前
<LibraryType .....
假设你的库类型是
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>