Deserializing xml into object returns null - c#

It counts correctly the number of objects but returns null or zero.I have lots of a lot of classes to fill with xml content.I need an efficient method to import xml to my C# app. Is my xml file corrupt?
Xml file:
<Entitati>
<Entitate>
<nume>asd</nume>
<actiuni>25</actiuni>
<valoare>2.05</valoare>
</Entitate>
<Entitate>
<nume>fgh</nume>
<actiuni>50</actiuni>
<valoare>3.14</valoare>
</Entitate>
<Entitate>
<nume>fanel</nume>
<actiuni>35</actiuni>
<valoare>5.15</valoare>
</Entitate>
</Entitati>
Classes:
[XmlRoot("Entitati")]
public class Entitati
{
[XmlElement("Entitate")]
public List<Entitate> entitati { get; set; }
}
[XmlRoot("Entitate")]
public class Entitate
{
[XmlElement("nume")]
protected string nume { get; set; }
[XmlElement("actiuni")]
protected int actiuniDisponibile { get; set; }
[XmlElement("valoare")]
protected double valoareActiune { get; set; }
}
Main:
XmlSerializer serializer = new XmlSerializer(typeof(Entitati));
using (FileStream fileStream = new
FileStream("C:\\Users\\batrinut\\Desktop\\Entitati.xml", FileMode.Open))
{
Entitati result = (Entitati)serializer.Deserialize(fileStream);
}

The properties in the Entitate class should not be protected.
Changing then to public should do the trick.
namespace SOTest
{
class Program
{
static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(Entitati));
using (FileStream fileStream = new FileStream("data.xml", FileMode.Open))
{
Entitati result = (Entitati)serializer.Deserialize(fileStream);
Console.ReadKey();
}
}
}
[XmlRoot("Entitati")]
public class Entitati
{
[XmlElement("Entitate")]
public List<Entitate> entitati { get; set; }
}
[XmlRoot("Entitate")]
public class Entitate
{
[XmlElement("nume")]
public string nume { get; set; }
[XmlElement("actiuni")]
public int actiuniDisponibile { get; set; }
[XmlElement("valoare")]
public double valoareActiune { get; set; }
}
}

Related

Deserialize XML with XmlSerializer where parent and child have the same tag

I'm having difficulty parsing an XML string where the parent and child nodes have the same tag name. Obviously, I could replace the open/close tags with empty strings and parse with the code below, but that's not elegant.
I've searched and see that there are answers for how to do this with XDocument, but I specifically would like to do this with XmlSerializer (if possible).
Below is a minimal, reproducable example.
Example XML:
<AddJob>
<AddJob RequestStatus="OK" RequestMessage="Job successfuly added [testPrintServer.tif, PES_Carpet_16C_76.2 x 50.8 dpi_170517_Normal]" UUID="74ad5971-7baf-49ce-b85b-ee08188d5721" />
</AddJob>
Parsing code:
public class XmlHelper
{
public static T Deserialize<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
T result;
using (var reader = new StringReader(xml))
{
result = (T)serializer.Deserialize(reader);
}
return result;
}
}
Data model:
[XmlRoot("AddJob")]
public class AddJob
{
[XmlAttribute]
public string RequestStatus { get; set; }
[XmlAttribute]
public string RequestMessage { get; set; }
[XmlAttribute("UUID")]
public string RipJobId { get; set; }
}
Calling code:
var addedJobResponse = XmlHelper.Deserialize<AddJob>(exampleXml);
Your data model doesn't match your xml structure.
Please use something like that:
[XmlRoot("AddJob")]
public class AddJob
{
[XmlElement(ElementName = "AddJob")]
public List<NestedAddJob> AddJobs { get; set; }
}
public class NestedAddJob
{
[XmlAttribute]
public string RequestStatus { get; set; }
[XmlAttribute]
public string RequestMessage { get; set; }
[XmlAttribute("UUID")]
public string RipJobId { get; set; }
}
The nested AddJob elements look like an array and you cannot have an array at the root. So add a Root class like code below :
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication75
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string xml = "<AddJob>" +
"<AddJob RequestStatus=\"OK\" RequestMessage=\"Job successfuly added [testPrintServer.tif, PES_Carpet_16C_76.2 x 50.8 dpi_170517_Normal]\" UUID=\"74ad5971-7baf-49ce-b85b-ee08188d5721\" />" +
"</AddJob>";
Root job = XmlHelper.Deserialize<Root>(xml);
}
}
public class XmlHelper
{
public static T Deserialize<T>(string xml)
{
var serializer = new XmlSerializer(typeof(T));
T result;
using (var reader = new StringReader(xml))
{
result = (T)serializer.Deserialize(reader);
}
return result;
}
}
[XmlRoot("AddJob")]
public class Root
{
public AddJob AddJob { get; set; }
}
public class AddJob
{
[XmlAttribute]
public string RequestStatus { get; set; }
[XmlAttribute]
public string RequestMessage { get; set; }
[XmlAttribute("UUID")]
public string RipJobId { get; set; }
}
}

C# XML reading foreach always first value

My XML
<?xml version="1.0" encoding="UTF-8"?>
<teklif>
<bilgiler>
<firma>Firma Adı</firma>
<aciklama>Açıklama</aciklama>
<isim>Ad Soyad</isim>
<telefon>Telefon</telefon>
<eposta>E Posta</eposta>
<urunler>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>Ürün Açıklaması</aciklama>
<birim>3,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>Ürün Açıklaması</aciklama>
<birim>5,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
<urun>
<resimDosyasi>Dosya Seçilmedi</resimDosyasi>
<aciklama>aas</aciklama>
<birim>2,00</birim>
<miktar>1</miktar>
<toplam>0,00</toplam>
</urun>
</urunler>
And My Function which reads the XML file
XmlDocument doc = new XmlDocument();
doc.Load(filename);
XmlNodeList xmllist = doc.SelectNodes("/teklif/bilgiler/urunler");
foreach(XmlNode nod in xmllist)
{
foreach(XmlNode childNode in nod.ChildNodes)
{
// her ürünün childnode oldu
if(childNode.Name == "#text")
{
} else
{
var urun_resim = childNode.SelectSingleNode("//resimDosyasi").InnerText;
var urun_aciklama = childNode.SelectSingleNode("//aciklama").InnerText;
var urun_birim = childNode.SelectSingleNode("//birim").InnerText;
MessageBox.Show(urun_birim);
var urun_miktar = childNode.SelectSingleNode("//miktar").InnerText;
var urun_toplam = childNode.SelectSingleNode("//toplam").InnerText;
var urun = new Urun(urun_resim, urun_birim, urun_miktar, urun_aciklama);
lw_urunler.Items.Add(urun);
}
}
}
The problem is when I message box the //birim in foreach loop, it always writes the first one - 3,00((3 times). As you can see in XML, first is 3,00, the second is 5,00 and the third is 2,00 but it always writes the first one. I checked up a lot but I can't see the problem.
Try it without the //, e.g. childNode.SelectSingleNode("birim"). Two forward slashes mean the root of the XML document, and my guess is it's just always finding the first birim node starting from the root each time.
The // means to select nodes no matter where they are under the current context. Current context defaults to the root. To limit the results to those under the current child node follow this pattern (just add a dot):
var urun_resim = childNode.SelectSingleNode(".//resimDosyasi").InnerText;
Using xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication52
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
List<urun> uruns = doc.Descendants("urun").Select(x => new urun() {
resimDosyasi = (string)x.Element("resimDosyasi"),
aciklama = (string)x.Element("aciklama"),
birim = (string)x.Element("birim"),
miktar = (int)x.Element("miktar"),
toplam = (string)x.Element("toplam")
}).ToList();
}
}
public class urun
{
public string resimDosyasi { get; set; }
public string aciklama { get; set; }
public string birim { get; set; }
public int miktar { get; set; }
public string toplam { get; set; }
}
}
Another approach that would increase the readability and maintenance of your code would be to map the XML schema into an object model.
Doing so, you could easly load the XML data as follows:
XmlSerializer serializer = new XmlSerializer(typeof(Teklif));
using (FileStream fileStream = new FileStream(filename, FileMode.Open))
{
Teklif result = (Teklif)serializer.Deserialize(fileStream);
}
// Object model example
[XmlRoot("teklif")]
public class Teklif
{
[XmlElement()]
public bilgiler bilgiler { get; set; }
}
public class bilgiler
{
[XmlElement()] public string firma { get; set; }
[XmlElement()] public string aciklama { get; set; }
[XmlElement()] public string isim { get; set; }
[XmlElement()] public string telefon { get; set; }
[XmlElement()] public string eposta { get; set; }
[XmlArray()]
[XmlArrayItem("urun")]
public List<Urun> urunler { get; set; }
}
public class Urun
{
[XmlElement()] public string resimDosyasi { get; set; }
[XmlElement()] public string aciklama { get; set; }
[XmlElement()] public string birim { get; set; }
[XmlElement()] public int miktar { get; set; }
[XmlElement()] public string toplam { get; set; }
}

Deserialize a class with list of class containing a list: Error: "the collection is read-only"

I'd like to serialize a class construct that contains a list of up to 16 sensors ( and additional a list with up to 4 PressureSensors), which contain a list with the coefficients of their function (and some more information like ID ...).
The PressureSensor thing is additional and just shows that there are some more collections in the module. Otherwise a
List<List<SimpleSensor>>
would have been sufficient.
The XML is created without problems, only deserialization fails
<?xml version="1.0" encoding="utf-8"?>
<Module xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SingleSensors>
<SSensor>
<ID>Sensor1</ID>
<Function>
<double>0</double>
<double>1</double>
</Function>
</SSensor>
<SSensor>
<ID>Sensor2</ID>
<Function>
<double>0</double>
<double>1</double>
</Function>
</SSensor>
</SingleSensors>
<PressureSensors>
<PSensor>
<ID>Pressure1</ID>
<Function>
<double>0</double>
<double>1</double>
</Function>
</PSensor>
<PSensor>
<ID>Pressure2</ID>
<Function>
<double>0</double>
<double>1</double>
</Function>
</PSensor>
</PressureSensors>
</Module>
The Class construct is as follows:
[Serializable]
public class SimpleSensor
{
[XmlElement("ID")]
public string Id { get; set; }
[XmlArray("Function")]
public Collection<double> Coefficient { get; set; }
//## Constructor:
public SimpleSensor()
{
Id = "00";
double[] content = new double[2] { 0, 1 };
Coefficient = new Collection<double>(content);
}
}
[Serializable]
[XmlRoot("Module")]
public class MostModule
{
[XmlArray("SingleSensors")]
[XmlArrayItem("SSensor")]
public List<SimpleSensor> Sensor { get; set; }
[XmlArray("PressureSensors")]
[XmlArrayItem("PSensor")]
public List<SimpleSensor> PressureSensor { get; set; }
//## Constructor:
public MostModule()
{
//Initialise SimpleSensors with 2 Sensors
SimpleSensor[] SensorArray = new SimpleSensor[2];
for (int i = 0; i < 2; i++)
{
SensorArray[i] = new SimpleSensor();
SensorArray[i].Id = "Sensor" + (i + 1);
}
Sensor = new List<SimpleSensor>(SensorArray);
PressureSensor = new List<SimpleSensor>(SensorArray);
}
public static MostModule Deserialize(string fileName)
{
MostModule Sensors;
XmlSerializer myXMLSerial = new XmlSerializer(typeof(MostModule));
using (StreamReader sr = File.OpenText(fileName))
{
Sensors = (MostModule)myXMLSerial.Deserialize(sr);
}
return Sensors;
}
When I tried to Serialize this class it works properly, but the deserialization stops with an error and the inner exception:
NotSupportedException "The collection is read-only."
I have tried the same with hard defined sensors and there is no problem in Serializing and deserializing:
public class MostModule
{
public SimpleSensor Sensor1 { get; set; }
public SimpleSensor Sensor2 { get; set; }
Is there a way to serialize the module this way, or do I have to program it all with hard defined Variables that i have to put into a list from the main?
Or is there any other suggestion for saving and loading my data in this kind of construction?
I made the following List<> objects
[XmlRoot("SingleSensors")]
public class SimpleSensor
{
[XmlElement("SSensor")]
public List<SSensor> sSensor { get; set; }
}
[XmlRoot("PressureSensors")]
public class PressureSensors
{
[XmlElement("PSensor")]
public List<SSensor> sSensor { get; set; }
}
Define SimpleSensor.Coefficient as a plain array and it will work:
[Serializable]
public class SimpleSensor
{
[XmlElement("ID")]
public string Id { get; set; }
[XmlArray("Function")]
public double[] Coefficient { get; set; }
//## Constructor:
public SimpleSensor()
{
Id = "00";
double[] content = new double[2] { 0, 1 };
Coefficient = content;
}
}
Try this
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication27
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlSerializer xs = new XmlSerializer(typeof(MostModule));
XmlTextReader reader = new XmlTextReader(FILENAME);
MostModule MostModule = (MostModule)xs.Deserialize(reader);
}
}
[XmlRoot("Function")]
public class Function
{
[XmlElement("double")]
public List<int> m_double {get;set;}
}
public class SSensor
{
[XmlElement("ID")]
public string Id { get; set; }
[XmlElement("Function")]
public Function Coefficient { get; set; }
}
[XmlRoot("SingleSensors")]
public class SimpleSensor
{
[XmlElement("SSensor")]
public SSensor sSensor { get; set; }
}
[XmlRoot("PressureSensors")]
public class PressureSensors
{
[XmlElement("PSensor")]
public SSensor sSensor { get; set; }
}
[XmlRoot("Module")]
public class MostModule
{
[XmlElement("SingleSensors")]
public SimpleSensor Sensor { get; set; }
[XmlElement("PressureSensors")]
public PressureSensors PressureSensor { get; set; }
}
}

C# Deserializing nested xml

I have the following code to deseriaze an xml string in C#.
Everything works fine and I am able to deserialize it to an object. However, the ProjectNode value is always empty.
Can someone please help me make this code work or point out what am I missing?
The sample XML has been included in the code below.
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace DeserializeSample
{
class Program
{
static string XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><response clientos=\"Windows\" datetimepattern=\"M/d/yyyy h:mm:ss a\"><info><![CDATA[<?xml version=\"1.0\" encoding=\"UTF-8\"?><transaction loglevel=\"0\" type=\"response\"><arguments><argument name=\"id\">1</argument><argument name=\"foredit\">True</argument><argument name=\"ScheduleOn\">Estimated</argument><argument name=\"xml\"><Project xmlns=\"http://schemas.microsoft.com/project\"><UID>0</UID><ID>0</ID></Project></argument></arguments></transaction>]]></info></response>";
static void Main(string[] args)
{
ProjectResponse projectResponse = CreateFromXml(XML, typeof(ProjectResponse)) as ProjectResponse;
}
public static object CreateFromXml(string data, Type msfRequestResponseType)
{
object projectResponse = null;
try
{
XmlSerializer deserializer = new XmlSerializer(msfRequestResponseType, "");
XmlReaderSettings settings = new XmlReaderSettings() { ProhibitDtd = true };
// We have content in the part so create xml reader and load the xml into XElement.
using (XmlReader reader = XmlReader.Create(new StringReader(data), settings))
{
projectResponse = deserializer.Deserialize(reader);
}
}
catch (Exception Ex)
{
throw;
}
return projectResponse;
}
}
[XmlRoot("response")]
[Serializable]
public class ProjectResponse
{
[XmlAnyAttribute()]
public XmlAttribute[] ResponseAttributes { get; set; }
[XmlElement("info")]
public ProjectResponseInfoTag InfoTag { get; set; }
public class ProjectResponseInfoTag
{
private string infoText = string.Empty;
[XmlText]
public string InfoText
{
get { return infoText; }
set
{
infoText = value;
Transaction = Program.CreateFromXml(infoText, typeof(ProjectTransaction)) as ProjectTransaction;
}
}
[XmlElement("transaction")]
public ProjectTransaction Transaction { get; set; }
[XmlRoot("transaction")]
public class ProjectTransaction
{
[XmlAnyAttribute]
public XmlAttribute[] TransactionAttributes { get; set; }
[XmlElement("arguments")]
public ProjectArguments Arguments { get; set; }
public class ProjectArguments
{
[XmlElement("argument")]
public List<ProjectArgument> ArgList { get; set; }
public class ProjectArgument
{
[XmlAttribute("name")]
public string Name { get; set; }
[XmlText]
public string ArgValue { get; set; }
[XmlElement("Project")]
public Project ProjectNode { get; set; }
public class Project
{
[XmlAnyElement()]
public XmlElement[] ProjectElements { get; set; }
[XmlAnyAttribute()]
public XmlAttribute[] ProjectAttributes { get; set; }
}
}
}
}
}
}
}
Xml namespaces; try
[XmlElement("Project", Namespace="http://schemas.microsoft.com/project")]

Import Xml File and Bind to Object

I would like to import an xml file and deserialize it into my model objects.
I am using C# MVC4 Asp.Net 4.51
I have tried a number of methods - if someone can provide some guidance on the best way to achieve this it would be appreciated.
I have tried but cannot get this to work:
public static KronosPunchRoundRuleSummary Deserialize()
{
XmlSerializer serializer = new XmlSerializer(typeof(KronosPunchRoundRuleSummary));
TextReader textReader;
textReader = new StreamReader(#"c:\WSAPunchRoundRule.xml");
KronosPunchRoundRuleSummary summary = (KronosPunchRoundRuleSummary)serializer.Deserialize(textReader);
textReader.Close();
}
I have also tried thisenter code here but I get an error saying it does not expect Kronos_WFC xmlns:
public static KronosPunchRoundRuleSummary Deserialize()
{
//XmlSerializer serializer = new XmlSerializer(typeof(KronosPunchRoundRuleSummary));
//TextReader textReader;
//textReader = new StreamReader(#"c:\WSAPunchRoundRule.xml");
//KronosPunchRoundRuleSummary summary = (KronosPunchRoundRuleSummary)serializer.Deserialize(textReader);
//textReader.Close();
XmlDocument doc = new XmlDocument();
doc.Load(#"c:\WSAPunchRoundRule.xml");
string xmlcontents = doc.InnerXml;
return null;
}
The xml file looks like this
`<?xml version="1.0"?>
-<Kronos_WFC TimeStamp="03/12/2013 14:59 GMT+04:00" WFCVersion="6.2.11.231" VERSION="1.0">
-<Response action="RetrieveAllForUpdate" Status="Success">
<WSAPunchRoundRule OutPunchLateChangePoint="0:00" UnscheduledInGrace="0:00" OutPunchEarlyInsideRound="0:01" OutPunchEarlyOutsideGrace="0:00" Name="Default Early Start" OutPunchEarlyOutsideRound="0:01" UseScheduledOut="false" InPunchLateInsideGrace="0:00" InPunchLateInsideRound="0:01" OutPunchLateOutsideGrace="0:00" InPunchEarlyInsideGrace="0:00" UnscheduledInRound="0:01" InPunchEarlyChangePoint="2:00" InPunchLateOutsideGrace="0:00" InPunchLateOutsideRound="0:01" OutPunchLateInsideGrace="0:00" IsMissedOutException="true" TransferGrace="0:00" UnscheduledOutGrace="0:00" TransferRound="0:01" InPunchLateChangePoint="0:00" OutPunchLateInsideRound="0:01" OutPunchLateOutsideRound="0:01" OutPunchEarlyInsideGrace="0:00" OutPunchEarlyChangePoint="0:00" InPunchEarlyOutsideRound="0:01" InPunchEarlyOutsideGrace="0:00" UnscheduledOutRound="0:01" InPunchEarlyInsideRound="2:00"/>
<WSAPunchRoundRule OutPunchLateChangePoint="0:00" UnscheduledInGrace="0:00" OutPunchEarlyInsideRound="0:01" OutPunchEarlyOutsideGrace="0:00" Name="Ramadan" OutPunchEarlyOutsideRound="0:01" UseScheduledOut="false" InPunchLateInsideGrace="0:00" InPunchLateInsideRound="0:01" OutPunchLateOutsideGrace="0:00" InPunchEarlyInsideGrace="0:00" UnscheduledInRound="0:01" InPunchEarlyChangePoint="2:00" InPunchLateOutsideGrace="0:00" InPunchLateOutsideRound="0:01" OutPunchLateInsideGrace="0:00" IsMissedOutException="true" TransferGrace="0:00" UnscheduledOutGrace="0:00" TransferRound="0:01" InPunchLateChangePoint="0:00" OutPunchLateInsideRound="0:01" OutPunchLateOutsideRound="0:01" OutPunchEarlyInsideGrace="0:00" OutPunchEarlyChangePoint="0:00" InPunchEarlyOutsideRound="0:01" InPunchEarlyOutsideGrace="0:00" UnscheduledOutRound="0:01" InPunchEarlyInsideRound="2:00"/>
<WSAPunchRoundRule OutPunchLateChangePoint="0:00" UnscheduledInGrace="0:00" OutPunchEarlyInsideRound="0:01" OutPunchEarlyOutsideGrace="0:00" Name="Transfer Rounding" OutPunchEarlyOutsideRound="0:01" UseScheduledOut="true" InPunchLateInsideGrace="0:00" InPunchLateInsideRound="0:01" OutPunchLateOutsideGrace="0:00" InPunchEarlyInsideGrace="0:00" UnscheduledInRound="0:01" InPunchEarlyChangePoint="2:00" InPunchLateOutsideGrace="0:00" InPunchLateOutsideRound="0:01" OutPunchLateInsideGrace="0:00" IsMissedOutException="false" TransferGrace="0:00" UnscheduledOutGrace="0:00" TransferRound="0:01" InPunchLateChangePoint="0:00" OutPunchLateInsideRound="0:01" OutPunchLateOutsideRound="0:01" OutPunchEarlyInsideGrace="0:00" OutPunchEarlyChangePoint="0:00" InPunchEarlyOutsideRound="0:01" InPunchEarlyOutsideGrace="0:00" UnscheduledOutRound="0:01" InPunchEarlyInsideRound="2:00"/>
<WSAPunchRoundRule OutPunchLateChangePoint="0:00" UnscheduledInGrace="0:00" OutPunchEarlyInsideRound="0:01" OutPunchEarlyOutsideGrace="0:00" Name="Workrule Rounding" OutPunchEarlyOutsideRound="0:01" UseScheduledOut="false" InPunchLateInsideGrace="0:00" InPunchLateInsideRound="0:01" OutPunchLateOutsideGrace="0:00" InPunchEarlyInsideGrace="0:00" UnscheduledInRound="0:01" InPunchEarlyChangePoint="2:00" InPunchLateOutsideGrace="0:00" InPunchLateOutsideRound="0:01" OutPunchLateInsideGrace="0:00" IsMissedOutException="true" TransferGrace="0:00" UnscheduledOutGrace="0:00" TransferRound="0:01" InPunchLateChangePoint="0:00" OutPunchLateInsideRound="0:01" OutPunchLateOutsideRound="0:01" OutPunchEarlyInsideGrace="0:00" OutPunchEarlyChangePoint="0:00" InPunchEarlyOutsideRound="0:01" InPunchEarlyOutsideGrace="0:00" UnscheduledOutRound="0:01" InPunchEarlyInsideRound="2:00"/>
</Response>
</Kronos_WFC>`
My Class looks like this
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Xml.Linq;
using System.Xml;
using System.Web;
using System.Xml.Serialization;
using System.Data;
using System.Dynamic;
using System.Collections;
using System.IO;
namespace Mojito.Models
{
public class KronosPunchRoundRuleSummary
{
public List<KronosPunchRoundRule> kronosPunchRoundRules { get; set; }
}
public class KronosPunchRoundRule
{
public virtual int KronosPunchRoundRuleId { get; set; }
public virtual string Name { get; set; }
public virtual string OutPunchLateChangePoint { get; set; }
public virtual string UnscheduledInGrace { get; set; }
public virtual string OutPunchEarlyInsideRound { get; set; }
public virtual string OutPunchEarlyOutsideGrace { get; set; }
public virtual string OutPunchEarlyOutsideRound { get; set; }
public virtual string UseScheduledOut { get; set; }
public virtual string InPunchLateInsideGrace { get; set; }
public virtual string InPunchLateInsideRound { get; set; }
public virtual string OutPunchLateOutsideGrace { get; set; }
public virtual string InPunchEarlyInsideGrace { get; set; }
public virtual string UnscheduledInRound { get; set; }
public virtual string InPunchEarlyChangePoint { get; set; }
public virtual string InPunchLateOutsideGrace { get; set; }
public virtual string InPunchLateOutsideRound { get; set; }
public virtual string OutPunchLateInsideGrace { get; set; }
public virtual bool IsMissedOutException { get; set; }
public virtual string TransferGrace { get; set; }
public virtual string UnscheduledOutGrace { get; set; }
public virtual string TransferRound { get; set; }
public virtual string InPunchLateChangePoint { get; set; }
public virtual string OutPunchLateInsideRound { get; set; }
public virtual string OutPunchLateOutsideRound { get; set; }
public virtual string OutPunchEarlyInsideGrace { get; set; }
public virtual string OutPunchEarlyChangePoint { get; set; }
public virtual string InPunchEarlyOutsideRound { get; set; }
public virtual string InPunchEarlyOutsideGrace { get; set; }
public virtual string UnscheduledOutRound { get; set; }
public virtual string InPunchEarlyInsideRound { get; set; }
}
}
To do it I suggest you to read XML Serializer and Deserializer Tutorials.
XML Serialization and Deserialization: Part-1
Serialize/Deserialize any object to an XML file
Hope helps. Greetings!
UPDATE:
To serialize a unknown object you must pass all object a add to the serializer to say hwo the must serialize:
public static void Save<T>(T item, string filename, IEnumerable<Type> typeList) where T : class, new()
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), typeList.ToArray());
// To write to a file, create a StreamWriter object.
StreamWriter writer = null;
try
{
writer = new StreamWriter(filename);
var ns = new XmlSerializerNamespaces();
ns.Add(string.Empty, string.Empty);
xmlSerializer.Serialize(writer, item, ns);
}
catch (Exception ex)
{
}
finally
{
if (writer != null)
writer.Close();
}
}
To Deserialize unknown object its the same:
public static T Load<T>(string filename, IEnumerable<Type> typeList) where T : class, new()
{
if (!File.Exists(filename))
return new T();
TextReader fileStream = null;
try
{
// Construct an instance of the XmlSerializer with the type
// of object that is being deserialized.
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T), typeList.ToArray());
// To read the file, create a FileStream.
fileStream = new StreamReader(filename);
return xmlSerializer.Deserialize(fileStream) as T;
// Call the Deserialize method and cast to the object type.
// return xmlSerializer.Deserialize(fileStream) as T;
}
catch (Exception ex)
{
return new T();
}
finally
{
if (fileStream != null)
fileStream.Close();
}
}
UPDATE2:
T -> is the object you want to serialize.
filname -> the path/destinaton where you whant tu save it.
IEnumerable -> is a list of Types. Only declare a IEnumerable and Add all you type you will serialize there and after pass it on the Save, Load method.

Categories