我有一个简单的类,它继承自 Collection 并添加了几个属性。我需要将此类序列化为 XML,但 XMLSerializer 会忽略我的附加属性。
我认为这是因为 XMLSerializer 对 ICollection 和 IEnumerable 对象进行了特殊处理。解决这个问题的最佳方法是什么?
这是一些示例代码:
using System.Collections.ObjectModel;
using System.IO;
using System.Xml.Serialization;
namespace SerialiseCollection
{
class Program
{
static void Main(string[] args)
{
var c = new MyCollection();
c.Add("Hello");
c.Add("Goodbye");
var serializer = new XmlSerializer(typeof(MyCollection));
using (var writer = new StreamWriter("test.xml"))
serializer.Serialize(writer, c);
}
}
[XmlRoot("MyCollection")]
public class MyCollection : Collection<string>
{
[XmlAttribute()]
public string MyAttribute { get; set; }
public MyCollection()
{
this.MyAttribute = "SerializeThis";
}
}
}
这会输出以下 XML(注意 MyCollection 元素中缺少 MyAttribute):
<?xml version="1.0" encoding="utf-8"?>
<MyCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Hello</string>
<string>Goodbye</string>
</MyCollection>
What I want is
<MyCollection MyAttribute="SerializeThis"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>Hello</string>
<string>Goodbye</string>
</MyCollection>
有任何想法吗?越简单越好。谢谢。
集合通常不适合存放额外的属性。在序列化和数据绑定期间,如果项目看起来像集合(IList
, IEnumerable
等 - 取决于场景)。
如果是我,我会封装该集合 - 即
[Serializable]
public class MyCollectionWrapper {
[XmlAttribute]
public string SomeProp {get;set;} // custom props etc
[XmlAttribute]
public int SomeOtherProp {get;set;} // custom props etc
public Collection<string> Items {get;set;} // the items
}
另一种选择是实施IXmlSerializable
(相当多的工作),但这仍然不适用于数据绑定等。基本上,这不是预期的用法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)