Home > Misc > XML to strongly typed object in C#

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.
Composite XML

Composite XML

  • Copy the XML file content.
  • Open a new Class file “FruitsWrapper.cs” in Visual Studio 2012
  • Select “EDIT -> Paste Special -> Paste XML As Classes”
Paste Special XML As Class

Paste Special XML As Class

  • Now you get XML wrapper class on your Class file
Generated XML Wrapper Class

Generated XML Wrapper Class

  • 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.

Advertisement
Categories: Misc Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: