I'm trying to constrol where a class property is rendered when the class is serialized: I need the property to appear as an attribute on a specific element:
namespace ConsoleApplication6
{
public class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
myClass.MyList.Add(new Item() { ID = 1 });
myClass.MyList.Add(new Item() { ID = 2 });
myClass.Xxx = "Hello World!";
var sx = new XmlSerializer(myClass.GetType());
sx.Serialize(Console.Out, myClass);
}
public class MyClass
{
public MyClass()
{
MyList = new List<Item>();
}
public List<Item> MyList { get; set; }
[XmlAttributeAttribute(AttributeName = "x")]
public string Xxx { get; set; }
}
public class Item
{
public int ID { get; set; }
}
}
}
This serializes quite nicely into this:
<?xml version="1.0" encoding="ibm850"?>
<MyClass xmlns:xsi=" ... " xmlns:xsd=" ... " x="Hello World!">
<MyList>
<Item>
<ID>1</ID>
</Item>
<Item>
<ID>2</ID>
</Item>
</MyList>
</MyClass>
BUT: My problem is, I need the property Xxx
to be rendered as an attribute on the <MyList>
element rather than the <MyClass>
root element, like this:
...
<MyList x="Hello World!">
...
I'm GUESSING this should be possible using XmlSerialization attributes on the class/properties, but I can't figure it out. I even tried creating a subclass of List adding the property Xxx
to that, but the .NET XML serialization ignores the extra properties, and the XML output is just like the List<..> is normally serialized.
Update: Here's the code where I try to create a "custom list", that inherits from List<Item>
and adds an extra property:
public class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
myClass.MyList.Add(new Item() { ID = 1 });
myClass.MyList.Add(new Item() { ID = 2 });
myClass.MyList.Xxx = "Hello World!";
var sx = new XmlSerializer(myClass.GetType());
sx.Serialize(Console.Out, myClass);
}
public class MyClass
{
public MyClass()
{
MyList = new CustomList();
}
public CustomList MyList { get; set; }
}
public class Item
{
public int ID { get; set; }
}
public class CustomList : List<Item>
{
[XmlAttributeAttribute(AttributeName = "x")]
public string Xxx { get; set; }
}
}
The output xml looks like this:
<?xml version="1.0" encoding="ibm850"?>
<MyClass xmlns:xsi=" ... " xmlns:xsd=" ... ">
<MyList>
<Item>
<ID>1</ID>
</Item>
<Item>
<ID>2</ID>
</Item>
</MyList>
</MyClass>
Notice how the Xxx
property is not represented in the xml...