Generate xml files based on my C # classes

I have an xml file that I need to update every time in accordance with the requirements of a new client. in most cases, the xml is not correct due to manual updating of the xml file. I am thinking of writing a program (web / windows) where the correct check is provided. and based on input from ui i'm going to create an xml file. below is my xml file example.

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

can someone help me what would be the best approach for this?

+6
source share
1 answer

Create the following classes to store your data and validate:

 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 eg with RegEx _postCode = value; } } } public class RegisteredAddress : Address { } public class TradingAddress : Address { } 

And serialize this instance of the community class in xml:

 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(Community)); serializer.Serialize(File.Create("file.xml"), community); 

I think a little googling will help you understand how to deserialize a community object from a file.

+11
source

All Articles