Reputation: 13
[XmlRootAttribute("ls")]
public class Request<T>
{
[XmlAttribute("ver")]
public string Version { get; set; }
[XmlElement("hdr")]
public Header Header { get; set; }
[XmlElement(Type = typeof(class2), ElementName = "ChildClass")]
public T Data { get; set; }
}
[XmlRoot("ChildClass")]
public class class2
{
[XmlElement("login")]
public string Property1{ get; set; }
}
[XmlRoot("ChildClass3")]
public class class3
{
[XmlElement("User")]
public string Property1{ get; set; }
}
When Request<class2>
is serialized , Element name is "Data". I want element Name to be "ChildClass". when Request<class3>
is serialized , Element name should be "ChildClass3".
How can i do that
Upvotes: 1
Views: 78
Reputation: 4679
As far as I know the element name must be known at compile time and so you can't try and use the Data objects XmlRoot or class name or similar as these aren't known at compile time. You'll need to define every possible type that you could expect Data
to be set to. As follows:
[XmlRoot("ls")]
public class Request
{
[XmlAttribute("ver")]
public string Version { get; set; }
[XmlElement("ChildClass2",typeof(class2))]
[XmlElement("ChildClass3",typeof(class3))]
public object Data { get; set; }
}
public class class2
{
[XmlElement("login")]
public string Property1 { get; set; }
}
public class class3
{
[XmlElement("User")]
public string Property1 { get; set; }
}
The following two objects:
var exampleObject = new Request
{
Version = "versionExample",
Data = new class2 { Property1 = "property1Example" }
};
var exampleObject2 = new Request
{
Version = "versionExample",
Data = new class3 { Property1 = "property1Example" }
};
Then serialized to:
<ls ver="versionExample">
<ChildClass2>
<login>property1Example</login>
</ChildClass2>
</ls>
<ls ver="versionExample">
<ChildClass3>
<User>property1Example</User>
</ChildClass3>
</ls>
Upvotes: 1