First of all how to parse a predefined XML structure to a class object in C#
Sample XML:
<User> <Name>Joseph Lawrence</Name> <Class>Second</Class> <Section>B</Section> <Roll_number>2735</Roll_number> <Joining_Dt>20160323</Joining_Dt> </User>
Above sample can be parsed by creating a class and setting each variable to it’s respective XML attribute. See below:
[XmlRoot(ElementName = "User")] public class User { [XmlElement(ElementName = "Name")] public string Name { get; set; } [XmlElement(ElementName = "Class")] public string Class { get; set; } [XmlElement(ElementName = "Section")] public string Section { get; set; } [XmlElement(ElementName = "Roll_number")] public string Roll_number { get; set; } [XmlElement(ElementName = "Joining_Dt")] public string Joining_Dt { get; set; } }
Code to convert XML to object of User class:
string contents = File.ReadAllText(xmlstring); XmlSerializer serializer = new XmlSerializer(typeof(User)); StringReader rdr = new StringReader(contents); User resultingMessage = (User)serializer.Deserialize(rdr);
But sometimes fields vary from XML to XML or when some of these fields are changed in the xml, classes will need to be modified again. So a better approach is to create dynamic object using C# inbuilt class “ExpandObject” that will parse a dictionary to dynamic object. This can be used for further processing.
Convert XML to key-value pair dictionary and pass to below method:
var dynamicObject = new ExpandoObject() as IDictionary<string, Object>; foreach (var property in properties) { dynamicObject.Add(property.Key, property.Value); }
Get field values back from the dynamic object: Since dynamic object created above is of Dictionary<string, Object> type, it can be accessed by iterating as below:
foreach (KeyValuePair<string, object> kvp in dynamicObject) { // iterating over it gives the Properties and Values as a KeyValuePair System.Diagnostics.Debug.WriteLine("{0} = {1}", kvp.Key, kvp.Value); }