Friday, 13 March 2015

Generate xml files based on c# classes


I have a class file which had generated from xsd, now I want to construct xml.
Step1.
Get Your Class file. (This one has generated from .xsd)
public class Community
{
public string Author { get; set; }
public int CommunityId { get; set; }
public string Name { get; set; }
[XmlArray]
[XmlArrayItem(typeof(RegisteredAddress))]
[XmlArrayItem(typeof(TradingAddress))]
public List<Address> Addresses { get; set; }
}
public class Address
{
private string _postCode;
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PostCode
{
get { return _postCode; }
set {
// validate post code e.g. with RegEx
_postCode = value;
}
}
}
public class RegisteredAddress : Address { }
public class TradingAddress : Address { }
-------------
Now I have to generate .xml file.
Write console application using C#.
Open .cs file
Inside main add below code..
---------------------------
Community community = new Community {
Author = "xxx xxx",
CommunityId = 0,
Name = "name of community",
Addresses = new List<Address> {
new RegisteredAddress {
AddressLine1 = "xxx",
AddressLine2 = "xxx",
AddressLine3 = "xxx",
City = "xx",
Country = "xxxx",
PostCode = "0000-00"
},
new TradingAddress {
AddressLine1 = "zz",
AddressLine2 = "xxx"
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(xml_output));
TextWriter writer = new StreamWriter(@"C:\\sample.xml");
serializer.Serialize(writer, community);
--------------------
OUTPUT
------------
<community>
<author>xxx xxx</author>
<communityid>000</communityid>
<name>name of the community</name>
<addresses>
<registeredaddress>
<addressline1>xxx</addressline1>
<addressline2>xxx</addressline2>
<addressline3>xxx</addressline3>
<city>xxx</city>
<county>xx</county>
<postcode>0000-000</postcode>
<country>xxx</country>
</registeredaddress>
<tradingaddress>
<addressline1>xxx</addressline1>
<addressline2>xxx</addressline2>
<addressline3>xxx</addressline3>
<city>xxx</city>
<county>xx</county>
<postcode>0000-000</postcode>
<country>xxx</country>
</tradingaddress>
</addresses>
<community>
view raw gistfile1.cs hosted with ❤ by GitHub