1

I have this XML file format (coming from a third party API):

<root>
    <parameter name="id">189880</parameter>
    <parameter name="target">2c92c0f83ff55b4b014007d6194e1bed</parameter>
    <parameter name="account">2c92c0f93fd531f1013feed6c1095259</parameter>
    <parameter name="contact">Laurie</parameter>
</root>

This file can contains between 1 and 50 lines describing a different property for each line.

I want to dynamically convert it to a C# object. Each line of the file will become a property and be populated by the corresponding value.

Example based on the XML above:

public class Result
{
    public string id { get; set; }
    public string target { get; set; }
    public string account { get; set; }
    public string contact { get; set; }
}

Edit :

Let's simplify the problem. Let's assume that the file structure is fixed (for example always the 4 lines attributes described above )

Hassan
  • 1,413
  • 1
  • 10
  • 12
  • possible duplicate of [How do I map XML to C# objects](http://stackoverflow.com/questions/87621/how-do-i-map-xml-to-c-sharp-objects) – Kevin Jul 22 '13 at 22:51
  • There is no such thing as "dynamically convert to a [strongly typed] C# object" (at least not strongly typed above the DOM/Tree level). Kirill's approach will save some manually creation of DTO/annotation classes, which could be handy. Once there *is* a DTO/annotation class then something like XmlSerializer is easy to use. – user2246674 Jul 22 '13 at 22:54
  • And how you are going to use type, which you created dynamically? `var x = BuildSomethingFrom(xml); x.???` – Sergey Berezovskiy Jul 24 '13 at 17:33

2 Answers2

1

Use Xsd.exe tool to generate C# class from XML. Then use XmlSerializer to deserialize object.

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • I already managed to deserialize the XML object. But as the XML file can change from 1 to 50 lines I am not able to create dynamically the corresponding C# object – Hassan Jul 23 '13 at 05:24
  • Thank you but It's not what I am looking for. Please check my question again (2nd part of it) I need a strongly typed object. Maintaining the code using a Dictionnary will be a pain. – Hassan Jul 24 '13 at 17:26
  • @Massanu, Therefore you have two options: generate class as I mentioned in my answer or create it manually. – Kirill Polishchuk Jul 24 '13 at 22:10
1

You are better off using a Dictionary<T,T> - http://msdn.microsoft.com/en-us/library/xfhwa508.aspx with key/value pairs, if the properties will be dynamically changing.

Cam Bruce
  • 5,632
  • 19
  • 34
  • Thank you but It's not what I am looking for. Please check my question again (2nd part of it) I need a strongly typed object. Maintaining the code using a Dictionnary will be a pain. – Hassan Jul 24 '13 at 17:28
  • Create a class with every possible property, then parse the XML, while checking every attribute if it's null or not, and appropriately setting them, based on the check. – Cam Bruce Jul 24 '13 at 17:36