C# XML Serialization with custom type property

  • Thread starter Thread starter hpposch
  • Start date Start date
H

hpposch

Guest
Hi all,

i have a very special use case and i need your help :)

I have the following xml:

<?xml version="1.0" encoding="utf-8"?>
<Main>
<Workspace>
<W p3:type="Office" CommonProperty="1" Type="Office" OfficeProperty="2" xmlns:p3="http://www.w3.org/2001/XMLSchema-instance" />
<W p3:type="Home" CommonProperty="1" Type="Home" HomeProperty="2" xmlns:p3="http://www.w3.org/2001/XMLSchema-instance" />
</Workspace>
</Main>


In general this looks good for me, but i don't want the serializer to add the type information automatically because i already have the type as a Property declared.

Here is what i expect:

<?xml version="1.0" encoding="utf-8"?>
<Main>
<Workspace>
<W Type="Office" CommonProperty="1" OfficeProperty="2"/>
<W Type="Home" CommonProperty="1" HomeProperty="2"/>
</Workspace>
</Main>


And here are the classes for this structure:

public class Main
{
public List<W> Workspace { get; set; }

public Main()
{
Workspace = new List<W>();
Workspace.Add(new Office());
Workspace.Add(new Home());
}
}


[XmlInclude(typeof(Office))]
[XmlInclude(typeof(Home))]
public class W
{
[XmlAttribute]
public int CommonProperty { get; set; }
[XmlAttribute]
public string Type { get; set; }

public W()
{
Type = this.GetType().Name;
CommonProperty = 1;
}
}

public class Office : W
{
[XmlAttribute]
public int OfficeProperty { get; set; }

public Office()
{
OfficeProperty = 2;
}
}
public class Home : W
{
[XmlAttribute]
public int HomeProperty { get; set; }

public Home()
{
HomeProperty = 2;
}
}


I hope it is clear what i want and hopefully someone knows the answer.
I can not change the structure of the XML since it is given and it must be like that.
So i really need to serialize and deserialze everything to this format.

Thanks in advance for your help! :)

Continue reading...
 
Back
Top