C# Deserializing nested xml - c#

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")]

Related

There is an error in XML document (2, 2) when desearlizing xml to c# object

XML
<?xml version="1.0" encoding="UTF-8"?>
<orgc:Organizations xmlns:orgc="urn:workday.com/connector/orgs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<orgc:Organization>
<orgc:Organization_ID>SR1Code34</orgc:Organization_ID>
<orgc:Organization_Code>SR1Code34</orgc:Organization_Code>
<orgc:Organization_Type>Cost_Center_Hierarchy</orgc:Organization_Type>
<orgc:Organization_Name>LTL Services</orgc:Organization_Name>
<orgc:Organization_Description>LTL Services</orgc:Organization_Description>
<orgc:Organization_Subtype>ORGANIZATION_SUBTYPE-3-20</orgc:Organization_Subtype>
<orgc:Inactive>false</orgc:Inactive>
<orgc:Superior_Organization>DL2Code11</orgc:Superior_Organization>
</orgc:Organization>
<orgc:Organization>
<orgc:Organization_ID>SR1Code35</orgc:Organization_ID>
<orgc:Organization_Code>SR1Code35</orgc:Organization_Code>
<orgc:Organization_Type>Cost_Center_Hierarchy</orgc:Organization_Type>
<orgc:Organization_Name>Consolidation</orgc:Organization_Name>
<orgc:Organization_Description>Consolidation</orgc:Organization_Description>
<orgc:Organization_Subtype>ORGANIZATION_SUBTYPE-3-20</orgc:Organization_Subtype>
<orgc:Inactive>false</orgc:Inactive>
<orgc:Superior_Organization>DL2Code11</orgc:Superior_Organization>
</orgc:Organization>
</orgc:Organizations>
Class
[XmlRoot(ElementName = "Organizations", Namespace = "urn: workday.com/connector/orgs", IsNullable = true )]
public class CostCenterHierarchy
{
[XmlElement("orgc:Organization_ID")]
public string CostCenterHierarchyId { get; set; }
[XmlElement("orgc:Organization_Code")]
public string Code { get; set; }
[XmlElement("orgc:Organization_Name")]
public string Name { get; set; }
[XmlElement("orgc:Organization_Description")]
public string Description { get; set; }
[XmlElement("orgc:Organization_Subtype")]
public string Subtype { get; set; }
[XmlElement("orgc:Superior_Organization")]
public string ParentHierarchyId { get; set; }
}
Method to deseralize xml to c# class
private List<CostCenterHierarchy> ProcessCostCenterHierarchy(string filePath)
{
var costCenterHierarchyList = new List<CostCenterHierarchy>();
//var costCenterHierarchy = new CostCenterHierarchy();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<CostCenterHierarchy>));
using (var reader = XmlReader.Create(filePath))
{
var test = xmlSerializer.Deserialize(reader);
}
return costCenterHierarchyList;
}
Error Message
Message = "There is an error in XML document (2, 2)."
InnerException = {"<Organizations xmlns='urn:workday.com/connector/orgs'> was not expected."}
I'm not sure where I am going wrong. Seems like it should be pretty easy but I've played around with this and keep getting the same error message. Any help would be much appreciated.
The code below works. You have an array and serialization doesn't like a list as the type. The Url "urn:workday.com/connector/orgs" the serializaer doesn't like and had to replace the "urn:" with "http://workday.com/connector/orgs".
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Organizations));
Organizations organizations = (Organizations)serializer.Deserialize(reader);
}
}
[XmlRoot(ElementName = "Organizations", Namespace = "http://workday.com/connector/orgs")]
public class Organizations
{
[XmlElement(ElementName = "Organization", Namespace = "http://workday.com/connector/orgs")]
public List<CostCenterHierarchy> organizations { get; set; }
}
public class CostCenterHierarchy
{
[XmlElement("Organization_ID")]
public string CostCenterHierarchyId { get; set; }
[XmlElement("Organization_Code")]
public string Code { get; set; }
[XmlElement("Organization_Name")]
public string Name { get; set; }
[XmlElement("Organization_Description")]
public string Description { get; set; }
[XmlElement("Organization_Subtype")]
public string Subtype { get; set; }
[XmlElement("Superior_Organization")]
public string ParentHierarchyId { get; set; }
}
}

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

Deserializing xml into object returns null

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

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.

add an attribute in an element that is parent of a list

I am trying to serialize an object but I am facing some issues regarding the attributes of a parent element that contains an array.
I have the following xml structure and I can't add the attribute in RatePlans element.
<Root>
<RatePlans Attribute="??this one??">
<RatePlan Attribute1="RPC" Attribute2="MC" Attribute3="RPT">
.
.
.
</RatePlan>
<RatePlan Attribute1="RPC2" Attribute2="MC3" Attribute3="RPT4">
.
.
.
</RatePlan>
</RatePlans>
</Root>
This is what I have done so far:
namespace XmlT {
[Serializable]
[XmlRoot("Root")]
public class Root {
public List<RatePlan> RatePlans { get; set; }
}
}
namespace XmlT {
[Serializable]
public class RatePlan {
[XmlAttribute]
public string RatePlanCode { get; set; }
[XmlAttribute]
public string MarketCode { get; set; }
[XmlAttribute]
public string RatePlanType { get; set; }
}
}
This gives me a correct structure but I don't know how to add the attribute I want
Another approach
I've tried also another approach but this gives me wrong values at all.
namespace XmlT {
[Serializable]
[XmlRoot("Root")]
public class Root {
public RatePlans RatePlans { get; set; }
}
}
namespace XmlT {
[Serializable]
public class RatePlans {
[XmlAttribute]
public string HotelCode { get; set; }
public List<RatePlan> RatePlan { get; set; }
}
}
EDIT
this the method that I am using for the serialization
protected static string Serialize<T>(object objToXml, bool IncludeNameSpace = false) where T : class {
StreamWriter stWriter = null;
XmlSerializer xmlSerializer;
string buffer;
try {
xmlSerializer = new XmlSerializer(typeof(T));
MemoryStream memStream = new MemoryStream();
stWriter = new StreamWriter(memStream);
if (!IncludeNameSpace) {
var xs = new XmlSerializerNamespaces();
xs.Add("", "");
xmlSerializer.Serialize(stWriter, objToXml, xs);
} else {
xmlSerializer.Serialize(stWriter, objToXml);
}
buffer = Encoding.ASCII.GetString(memStream.GetBuffer());
} catch (Exception Ex) {
throw Ex;
} finally {
if (stWriter != null) stWriter.Close();
}
return buffer;
}
Does anyone know how could I do this?
Thanks
If the RatePlans class from the 2nd example inherits from List<RatePlan> you will get the desired result:
[Serializable]
public class RatePlans: List<RatePlan>
{
[XmlAttribute]
public string HotelCode { get; set; }
}
Edit:
My bad. Fields of classes inheriting from collections will not be serialized. I didn't knew that. Sorry...
However, this solution works:
[Serializable]
[XmlRoot("Root")]
public class Root
{
public RatePlans RatePlans { get; set; }
}
[Serializable]
public class RatePlans
{
[XmlAttribute]
public string HotelCode { get; set; }
[XmlElement("RatePlan")]
public List<RatePlan> Items = new List<RatePlan>();
}

Categories