Converting XML into data object
Converting a Data object from an XML file just by using a Data class and XMLSerializer,
When you convert the XML to a data object, you need to make sure the XML structure matches the XML string provided.

The Data class
This is the data class. which will be used to convert the XML into a data object.
This should match the structure of the XML string.

public class ExampleDataClass
{
public string Type { get; set; }
public string Code { get; set; }
public string Description { get; set; }

public List ExampleElements { get; set; }
}



Required references

System.Xml.Serialization;



The Method Call
This will call the method, which will convert the String value into the ExampleDataClass object. This only needs a Class type and the string.
This example then casts the return object back into the ExmapleDataClass type.

ExampleDataClass dataClass = (ExampleDataClass )ObjectFromXMLString(typeof(ExampleDataClass ), x.XMLSTRING),



The converting method
This method converts the string to a Data object XMLSerializer

public static object ObjectFromXMLString(Type typeOfObject, string xmlFile)
{
if (String.IsNullOrEmpty(xmlFile))
return Activator.CreateInstance(typeOfObject);

XmlSerializer serializer = new XmlSerializer(typeOfObject);
StringReader rdr = new StringReader(xmlFile);
return serializer.Deserialize(rdr);
}
Created: 13/01/2017 Total Comment: 0

Comments

(Not Displayed)
Human validation
Enter 6295 number, before submitting to confirm your human
[Home] [All Blogs] [Contact] [Me]