控制XmlType将元素名称序列化
问题描述:
过程中我有一个类,是一个抽象类控制XmlType将元素名称序列化
[XmlInclude(typeof(PostedPayment))]
[XmlInclude(typeof(PostedInvoice))]
[XmlType("VoucherProgress")]
public class PostedJournals : List<APostedJournal>
{
public PostedJournals(IEnumerable<APostedJournal> postedJournals) : base(postedJournals) { }
public PostedJournals() { }
}
但是,当我序列化,我结束了
<VoucherProgress>
<APostedJournal p2:type="PostedPayment" xmlns:p2="http://www.w3.org/2001/XMLSchema-instance">
...
</APostedJournal>
</VoucherProgress>
列表时,我希望它的名字类型,不使用抽象名称
<VoucherProgress>
<PostedPayment>
...
</PostedPayment>
</VoucherProgress>
有没有办法使这项工作具有一些属性?
答
在这里,我给你这么远:
< ?xml version="1.0"?>
< MyList xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
< MyTypeBase />
< MySubType>something</ MySubType>
< MyTypeBase />
< MyTypeBase />
< MyOtherSubType>something</ MyOtherSubType>
< MyTypeBase />
< MyTypeBase />
< MySubType>something</ MySubType>
< MyTypeBase />
< MyTypeBase />
< MyOtherSubType>something</ MyOtherSubType>
< MyTypeBase />
< MyTypeBase />
< MySubType>something</ MySubType>
< MyTypeBase />
</ MyList >
(我不知道如何让XML粘贴在这荒凉的网站
类节目 { 静态无效的主要(字符串[]。参数) { MYLIST TMP =新MYLIST();
tmp.Add(new MySubType());
tmp.Add(new MyOtherSubType());
tmp.Add(new MySubType());
tmp.Add(new MyOtherSubType());
tmp.Add(new MySubType());
XmlSerializer xs = new XmlSerializer(typeof(MyList));
MemoryStream ms = new MemoryStream();
xs.Serialize(ms, tmp);
ms.Seek(0, SeekOrigin.Begin);
TextReader tr = new StreamReader(ms);
string xt = tr.ReadToEnd();
}
}
[XmlRoot(ElementName="MyList")]
public class MyList : List<MyTypeBase> { }
[XmlInclude(typeof(MySubType))]
public class MyTypeBase : IXmlSerializable
{
public int ID { get; set; }
protected virtual Type elType { get { return typeof(MyTypeBase); } }
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteEndElement();
writer.WriteStartElement(elType.Name);
writer.WriteValue("something");
writer.WriteEndElement();
writer.WriteStartElement("MyTypeBase");
}
}
public class MySubType : MyTypeBase, IXmlSerializable
{
public string Name { get; set; }
protected override Type elType { get { return typeof(MySubType); } }
}
public class MyOtherSubType : MyTypeBase, IXmlSerializable
{
public string Name { get; set; }
protected override Type elType { get { return typeof(MyOtherSubType); } }
}
的代码让你西澳列表nt,但有额外的MtTypeBase元素,你可以自己弄清楚。它所做的只是改变了基类的序列化方式。每个子类都将elType更改为它自己的类类型,以便基类可以使用它来完成它的工作。我已经花了很多时间在这里,所以你可以在这里形成。有很多方法可以改善这一点,并使其更加清洁。
这将如何使它根据哪个子类实际被序列化来选择正确的名称? – CaffGeek 2011-02-25 00:49:27
你不能。你正在序列化一个泛型类型的列表,它将被用作类型。您唯一的选择就是勾选序列化步骤并使其使用所需的类型。 GetType()将返回实例类型而不是基类型。您也可以创建自己的XmlName属性,只从现有的属性继承,并更改名称的方式。 – 2011-02-25 02:47:43
尝试一下代码。你可以从那里开始。这是一个有趣的挑战。 – 2011-02-26 06:09:50