I want to deserialize the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<Jobs>
<Job>
<Id>1</id>
<Description>d1</description>
</Job>
<Job>
<Id>2</id>
<Description>d2</description>
</Job>
</Jobs>
- I don't want to use XmlSerializer because it cannot set private members.
- I don't want to use DataContractSerialize because (I believe) elements order matters. my xml document comes from a 3rd party and elements order may change (because there may be additional elements in between)
So I tried to convert the XML to Json and deserialize the jsonstring:
public class Job
{
public string Id { private get; set; }
public string ThirdPartyId => $"third-party-id-{Id}";
public string Description { get; set; }
}
And this how I try to deserialize:
public List<Job> Deserialize(XDocument xDocument)
{
string jsonString = JsonConvert.SerializeXNode(xDocument);
return JsonConvert.DeserializeObject<List<Job>>(jsonString);
}
The above fails, I believe because the json contains "xml" node...
{"?xml":{"@version":"1.0","@encoding":"utf-8"},
"Jobs":{"Job":[{"Id":"1","Description":"D1"}, {"Id":"2","Description":"D2"}]}
Is it possible to remove the xml node from xDocument? Is there a better option for doing this?