Search code examples
c#.netxmldeserializationxml-deserialization

How to deserialize a xml string to a set of C# classes without having to declare a lot properties just for xml attributes?


I have the xml below and I am wondering how can it be deserialized to a set of classes without having to add tons of fields (to those classes) just for the sake of representing the different xml attributes (and their respective values).

I thought I could have something which support declarative xml attributes as .NET attributes on top properties that define xml elements.

<y:input xmlns:y='http://www.stuff.com/blahblah/42'>
    <y:datas>
        <y:instance yclass='Report' yid="report">
            <language yid='LANG_fr'/>
            <threshold>0.8</threshold>
            <typePeriod>predefinedPeriod</typePeriod>
            <interval>month</interval>
            <valuePeriod>April</valuePeriod>
            <fund yclass="Fund">
                <name>K</name>
                <performance yclass="Performance">
                    <typeValue>percent</typeValue>
                    <value>-0.05</value>
                </performance>
                [... lot of other fields ...]
            </fund>
        </y:instance>
    </y:datas>
</y:input>

Solution

  • You should be able to use ExpandoObject (part of System.Dynamic).

    I tried a quick solution myself and was able to parse that xml successfully to a dynamic object.

    What you need to do is:

    1. Parse the string data to XDocument so you have an xml document object.

      var doc = XDocument.Parse(xmlData);

    2. I then converted the doc to a json string, you don't need to do this but it was the quickest way for me to test if this will work. (For this I needed to add the Newtonsoft.Json NuGet package.)

      string jsonText = JsonConvert.SerializeXNode(doc);

    3. Then lastly I deserilzed the object like this:

      dynamic dyn = JsonConvert.DeserializeObject<ExpandoObject>(jsonText);