Paresh Makwana
Paresh Makwana

Reputation: 189

How to convert XML into Object format in C#

I wanted to convert this XML in to object format

- <information>
- <item>
  <key>Name</key> 
  <value>NameValue</value> 
  </item>
- <item>
  <key>Age</key> 
  <value>17</value> 
  </item>
- <item>
  <key>Gender</key> 
  <value>MALE</value> 
  </item>
- </information>

Object something like,

Person.Name = "Name Value"
Person.Age = 17
Person.Gender = "Male"

Upvotes: 2

Views: 1673

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

You can XDocument with reflection for achieving this following way:

XDocument XDocument = XDocument.Parse(MyXml);

var nodes = XDocument.Descendants("item");

// Get the type contained in the name string
Type type = typeof(Person);

// create an instance of that type
object instance = Activator.CreateInstance(type);

// iterate on all properties and set each value one by one

foreach (var property in type.GetProperties())
{

    // Set the value of the given property on the given instance
    if (nodes.Descendants("key").Any(x => x.Value == property.Name)) // check if Property is in the xml
    {
        // exists so pick the node
        var node = nodes.First(x => x.Descendants("key").First().Value == property.Name);  
        // set property value by converting to that type
        property.SetValue(instance,  Convert.ChangeType(node.Element("value").Value,property.PropertyType), null);
    }
}


var tempPerson = (Person) instance;

I made a Example Fiddle

It can also be made generic by refactoring it using Generics.

Upvotes: 2

sudhansu63
sudhansu63

Reputation: 6190

you can use XML Deserialization and Serialization to do this.

/// <summary>
/// Saves to an xml file
/// </summary>
/// <param name="FileName">File path of the new xml file</param>
public void Save(string FileName)
{
    using (var writer = new System.IO.StreamWriter(FileName))
    {
        var serializer = new XmlSerializer(this.GetType());
        serializer.Serialize(writer, this);
        writer.Flush();
    }
}

To create the object from the saved file, add the following function and replace [ObjectType] with the object type to be created.

/// <summary>
/// Load an object from an xml file
/// </summary>
/// <param name="FileName">Xml file name</param>
/// <returns>The object created from the xml file</returns>
public static [ObjectType] Load(string FileName)
{
    using (var stream = System.IO.File.OpenRead(FileName))
    {
        var serializer = new XmlSerializer(typeof([ObjectType]));
        return serializer.Deserialize(stream) as [ObjectType];
    }
}

Ref : Serialize an object to XML

Upvotes: 0

Related Questions