Esta es mi primera pregunta sobre Stack Overflow. Disculpas por adelantado si no hago las cosas bien mientras estoy aprendiendo cómo funcionan las cosas aquí.C# XML Serializer no almacenará un atributo
Aquí está mi código:
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; }
}
Produce este 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>
No entiendo por qué no estoy recibiendo <Items testAttribute="foo">
Por favor, ¿alguien puede decir lo que yo ¿Necesito agregar a mi código para que el serializador escriba este atributo?
Gracias,
@ martin-65, bienvenido a SO. Esta es una muy buena pregunta y debería servir como un ejemplo de cómo hacer preguntas incluso a usuarios más avezados en este sitio. Ha formateado correctamente su código, proporcionó un ejemplo de trabajo completo (que es fácil de reproducir en cualquier PC) aislando el problema, proporcionó el resultado del fragmento y explicó cuál es el resultado deseado. –
Gracias por la bienvenida y el aliento. – MartinC