这是我的第一个关于堆栈溢出的问题。如果在我学习这里的工作方式时我没有把事情做得很对,我会提前道歉。C#XML序列化程序不会存储属性
这里是我的代码:
public void TestSerialize()
{
ShoppingBag _shoppingBag = new ShoppingBag();
Fruits _fruits = new Fruits();
_fruits.testAttribute = "foo";
Fruit[] fruit = new Fruit[2];
fruit[0] = new Fruit("pineapple");
fruit[1]= new Fruit("kiwi");
_fruits.AddRange(fruit);
_shoppingBag.Items = _fruits;
Serialize<ShoppingBag>(_shoppingBag, @"C:\temp\shopping.xml");
}
public static void Serialize<T>(T objectToSerialize, string filePath) where T : class
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StreamWriter writer = new StreamWriter(filePath))
{
serializer.Serialize(writer, objectToSerialize);
}
}
[Serializable]
public class ShoppingBag
{
private Fruits _items;
public Fruits Items
{
get { return _items; }
set {_items = value; }
}
}
public class Fruits : List<Fruit>
{
public string testAttribute { get; set; }
}
[Serializable]
public class Fruit
{
public Fruit() { }
public Fruit(string value)
{
Name = value;
}
[XmlAttribute("name")]
public string Name { get; set; }
}
它生产这个XML:
<?xml version="1.0" encoding="utf-8" ?>
<ShoppingBag xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Items>
<Fruit name="pineapple" />
<Fruit name="kiwi" />
</Items>
</ShoppingBag>
我不明白为什么我没有得到<Items testAttribute="foo">
请谁能告诉我是什么需要添加到我的代码,以便序列化程序将这个属性写出来?
感谢,
@ martin-65,欢迎来到SO。这是一个很好的问题,应该成为如何向本网站上更多老用户提问的例子。您已经正确格式化了您的代码,提供了一个完整的工作示例(在任何PC上很容易重现)隔离问题,提供片段的输出并解释了期望的结果。 – 2010-08-28 19:13:32
感谢您的欢迎和鼓励。 – MartinC 2010-08-28 20:40:55