Converting Class to XML in C# 4.0

Converting your entire class data to XML and then XML to class back is very helpful when you are doing some project . Here I am explaining how to convert your class data to XML in C# 4.0 using System.Xml.Linq.

public class MyPackage
{
# region Private Variables Declaration
private string _packageCode;
private string _packageDescription;
private decimal _packageValue;
private int _mode;

# endregion
public MyPackage()
{

}
public MyPackage(int mode)
{

_mode = mode;
}
# region Properties Implementation
public string PackageCode
{
get { return _packageCode; }
set { _packageCode = value; }
}
public string PackageDescription
{
get { return _packageDescription; }
set { _packageDescription = value; }
}
public decimal PackageValue
{
get { return _packageValue; }
set { _packageValue = value; }
}
public int Mode
{
get { return _mode; }
set { _mode = value; }
}

#endregion
public string TransformClassToXML()
{
#region  Transform Current Class To XML

XDocument Xmldocument = null;
try
{
Xmldocument = new XDocument(
new XElement(“Package”,
new XElement(“PackageCode”, PackageCode),
new XElement(“PackageDescription”, PackageDescription),
new XElement(“PackageValue”, PackageValue),
new XElement(“Mode”, Mode)

)
);
}
catch (Exception ex)
{
string exp = ex.Message;

}
return Xmldocument.ToString();
#endregion
}

}

// converting back

public void TransformXMLToClass(string pXml)
{
// This function converts the xml back to class
# region Converting the XML to Class
XElement doc = XElement.Parse(pXml);
foreach(XElement el in doc.Elements(“Package”) )
{
MyPackage package = new MyPackage();

package.PackageCode = el.Element(“PackageCode”).Value;
package.PackageDescription = el.Element(“PackageDescription”).Value;
package.PackageValue = Convert.ToDecimal(el.Element(“PackageValue”).Value);
package.Mode = Convert.ToInt32(el.Element(“Mode”).Value);

}

# endregion

}

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s