-3

Below is my XML code.

<programs> <program> <ProgrameName>Test</ProgrameName> <deviceTypes> <DeviceType>POS</DeviceType> <deviceTargets> <DeviceNames> <DeviceName>POS0001</DeviceName> <DeviceName>POS0001</DeviceName> <DeviceName>POS0001</DeviceName> </DeviceNames> <AttemptToIstall>True</AttemptToIstall> <Mandetory>False</Mandetory> <SkipIfOffline>False</SkipIfOffline> </deviceTargets> <AttemptToIstall>True</AttemptToIstall> <Mandatory>False</Mandatory> <SkipIfOffline>False</SkipIfOffline> </deviceTypes> </program> 

please help me to write C# code using XmlSerializer.I want to create an object and serialize those object according to above XML.

below are my C# class.

 public class ProgramP { public string ProgrameName { get; set; } [XmlRoot("")] public class DeviceTypes { public string DeviceType { get; set; } [XmlRoot("")] public class DeviceTargets { public string DeviceNames { get; set; } public string AttemptToIstall { get; set; } public string Mandetory { get; set; } public string SkipIfOffline { get; set; } } [XmlElement("DeviceTargets")] public DeviceTargets[] ArDeviceTargets { get; set; } public string AttemptToIstall { get; set; } public string Mandetory { get; set; } public string SkipIfOffline { get; set; } } [XmlElement("DeviceTypes")] public DeviceTypes[] ArDeviceType { get; set; } } 

Below is my C# code.can any body please correct me or suggest me where i have to add more class or how can i arrange my class so that i can get above XML as output.

public void ExportClass(string strFilePathExportedXML) { ProgramP ProgramP = new ProgramP { ProgrameName = "Test", ArDeviceType = new ProgramP.DeviceTypes[] { new ProgramP.DeviceTypes { DeviceType = "POS1", AttemptToIstall="True", Mandetory="True", SkipIfOffline="True", ArDeviceTargets = new ProgramP.DeviceTypes.DeviceTargets[] { new ProgramP.DeviceTypes.DeviceTargets { DeviceNames="POS01", AttemptToIstall="True", Mandetory="True", SkipIfOffline="True" }, new ProgramP.DeviceTypes.DeviceTargets { DeviceNames="POS02", AttemptToIstall="True", Mandetory="True", SkipIfOffline="True" } } }; TextWriter writer = new StreamWriter(strFilePathExportedXML); XmlSerializer serializerOut = new XmlSerializer(typeof(ProgramP)); serializerOut.Serialize(writer, ProgramP); writer.Close(); 
1
  • 5
    What have you tried so far? Commented Jun 18, 2018 at 14:07

1 Answer 1

4

After mapping, you can use this:

public static YourClass LoadFromXMLString(string xmlText) { var stringReader = new System.IO.StringReader(xmlText); var serializer = new XmlSerializer(typeof(YourClass )); return serializer.Deserialize(stringReader) as YourClass ; } 

From this topic: Convert Xml to Object

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.