XML to strongly typed object in C#
Assume you have composite XML and you want read the XML field values in your C# project, the simplest way is to convert in to Strongly type object and read as parameters.
It involves two steps as mentioned below
Generate XML Wrapper Class
- “Fruits.xml” is your XML file.
- Copy the XML file content.
- Open a new Class file “FruitsWrapper.cs” in Visual Studio 2012
- Select “EDIT -> Paste Special -> Paste XML As Classes”
- Now you get XML wrapper class on your Class file
- Save the file
Convert XML to Class
- To test the Conversion and read the XML data
- Take a console application and paste below code
static void Main(string[] args){
const string fruitsXmlPath = @”c:\Fruits.xml”;
// Set your Root Element Name (i.e., <Fruits> is the root node of our XML)
var xRoot = new XmlRootAttribute { ElementName = “Fruits”, IsNullable = true };
var xmlSerializer = new XmlSerializer(typeof(Fruits), xRoot);
var fruits = (Fruits)xmlSerializer.Deserialize(new FileStream(fruitsXmlPath, FileMode.Open));
// Read XML node values as Object Properties
Console.WriteLine(“Fruit Name” + fruits.CitrusFruits.Fruit.Name);
Console.WriteLine(“Fruit Price” + fruits.CitrusFruits.Fruit.Price);
}
This approach is useful when you have your application’s configuration details provided in an XML file and if the file is complex and big.
Note – If you don’t have “Paste Special -> Paste XML As Classes” feature in your Visual Studio, you can use XSD.exe tool to generate wrapper class from XML.