这是我关于Stack Overflow的第一个问题。如果我在学习如何在这里工作的时候我不做正确的事情,请提前道歉。
这是我的代码:
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">
请有人告诉我需要添加到我的代码中,以便Serializer将此属性写出来吗?
谢谢,
答案 0 :(得分:2)
你需要一个中间课:
class Program
{
static void Main()
{
var shoppingBag = new ShoppingBag
{
Items = new ShoppingBagItems
{
Fruits = new List<Fruit>(new[] {
new Fruit { Name = "pineapple" },
new Fruit { Name = "kiwi" },
}),
TestAttribute = "foo"
}
};
var serializer = new XmlSerializer(typeof(ShoppingBag));
serializer.Serialize(Console.Out, shoppingBag);
}
}
public class ShoppingBag
{
public ShoppingBagItems Items { get; set; }
}
public class ShoppingBagItems
{
[XmlElement("Fruit")]
public List<Fruit> Fruits { get; set; }
[XmlAttribute("testAttribute")]
public string TestAttribute { get; set; }
}
public class Fruit
{
[XmlAttribute("name")]
public string Name { get; set; }
}
另请注意,您不需要使用[Serializable]
属性来装饰类,因为它仅用于二进制序列化。另一个注意事项是,您不需要从List<T>
派生,只需将其用作属性。
答案 1 :(得分:0)
不幸的是,在序列化集合时,XmlSerializer
没有考虑该集合的额外属性。它只考虑实施ICollection<T>
的成员。如果要序列化额外属性,则需要将该集合包装在另一个不是集合本身的类中。