I'm trying to serialize the Outer
class shown below, and create an XElement
from the serialized XML. It has a property which is of type Inner
. I'd like to change the name of both Inner
(to Inner_X
) and Outer
(to Outer_X
).
class Program
{
static void Main(string[] args)
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (TextWriter streamWriter = new StreamWriter(memoryStream))
{
var xmlSerializer = new XmlSerializer(typeof(Outer));
xmlSerializer.Serialize(streamWriter, new Outer());
XElement result = XElement.Parse(Encoding.ASCII.GetString(memoryStream.ToArray()));
}
}
}
}
[XmlType("Outer_X")]
public class Outer
{
public Outer()
{
this.InnerItem = new Inner();
}
public Inner InnerItem { get; set; }
}
[XmlType("Inner_X")]
public class Inner
{
}
This creates an XElement
which looks like this:
<Outer_X xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<InnerItem />
</Outer_X>
What I would like is:
<Outer_X xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Inner_X />
</Outer_X>
I want to keep the information about how a class should be renamed with that class. I thought I could do this with the XmlType
attribute. However, this is ignored and the property name is used instead.
I've looked here and here, amongst other places, and feel like this should work. What am I missing?
Clarification
By "keep(ing) the information about how a class should be renamed with that class", what I mean is that the term Inner_X
should only appear in the Inner
class. It should not appear at all in the Outer
class.