I’m calling a generic endpoint /api/foo
which returns an XML describing foo
. You can pass whatever entity name as foo
and it will return its data.
Below are some example of the responses.
When calling api/foo1
:
<foo1>
<name>SomeValue</name>
<id>101</id>
</foo1>
When calling api/foo2
:
<foo2>
<name>SomeOtherValue</name>
<id>205</id>
</foo2>
Basically the XML opens with the foo
parameter requested in the path. Fields inside (name, id) are fixed. The foo
entity names can be user defined, so there’s not a fixed known a-priori list I can work with.
I’m trying to deserialize the XML using this DataContractSerializer
and this DataContract
:
[DataContract(Name = "foo1", Namespace = "")]
public class Foo
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
}
Of course this works fine for foo1
, but doesn’t work for any other entity name.
Is it possible to somehow parameterize the DataContract
Name
at runtime? I’m building the serializer myself.
Minimal reproducible example here. The first assertion is working fine, second one is failing.
[DataContract(Name = "foo1", Namespace = "")]
public class Foo
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
}
[Fact]
public void TestDeserialization()
{
var foo1 = "<foo1>nt<name>SomeValue</name>nt<id>101</id>n</foo1>";
var foo2 = "<foo2>nt<name>SomeOtherValue</name>nt<id>205</id>n</foo2>";
var serializer = new DataContractSerializer(typeof(Foo));
var objFoo1 = (Foo)serializer.ReadObject(XmlReader.Create(new StringReader(foo1)));
var objFoo2 = (Foo)serializer.ReadObject(XmlReader.Create(new StringReader(foo2)));
bjFoo1.Name.Should().Be("SomeValue");
bjFoo2.Name.Should().Be("SomeOtherValue");
}