Mar*_*inC 5 c# xml-serialization
这是我关于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; }
}
Run Code Online (Sandbox Code Playgroud)
它产生这个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>
Run Code Online (Sandbox Code Playgroud)
我不明白为什么我没有得到 <Items testAttribute="foo">
请任何人都可以告诉我我需要添加到我的代码中,以便Serializer将此属性写出来?
谢谢,
不幸的是,在序列化集合时,XmlSerializer
没有考虑该集合的额外属性。它只考虑实施的成员ICollection<T>
。如果要序列化额外的属性,则需要将集合包装在另一个本身不是集合的类中。