Conversion from string to object in Windows 8.1 store app - c#

I want to covert to string into object with value. I mean let's say i have string that has XML code inside like:
string response = #"<?xml version=""1.0"" encoding=""utf-8""?>
<Response>
<ResultCode>0</ResultCode>
<ResultMessage>success</ResultMessage>
<Body>
<Rooms>
<Room>
<RoomID>room1#nxdev.com</RoomID>
<RoomName>White Room</RoomName>
<Capacity>10</Capicity>
<Equipments>Beam Projector, VTR</Equipments>
<Reservations>
<Reservation>
<StartDT> 2014-02-18 14:00</StartDT>
<EndDT>2014-02-18 15:00</EndDT>
<UserName>Jhon</UserName>
<Subject>Project Meeting</Subject>
<Reservation>
</Reservatoins>
</Room>
</Rooms>
</Body>
</Response>"
I have a Class that has all the properties which mentioned in Xml like
[XmlRoot("Response")]
public class Response
{
string ResultCode {get; set; }
string ResutlMessage { get; set; }
}
public class RoomListResponse : Response
{
List<Room> rooms { get; set; }
}
public class Room
{
[XmlElement("RoomID")]
string RoomID { get; set; }
[XmlElement("RoomName")]
string RoomName { get; set; }
[XmlElement("Capacity")]
string Capacity { get; set; }
[XmlElement("Equipments")]
string Equipments { get; set; }
List<Reservation> Reservations;
}
public class Reservations
{
[XmlElement("StartDT")]
string StartDT { get; set; }
[XmlElement("EndDT")]
string EndDT { get; set; }
[XmlElement("UserName")]
string UserName { get; set; }
[XmlElement("Subject")]
string Subject { get; set; }
}
How can I set all the values in RoomListResponse object without string parsing? I have tried it with serialization but it gives me some problem in windows 8.1 app store project due to limitation in API.
Is there any way to get it sorted?

Serialization is the only way.
In your case you might want to try replacing the
List<Reservation> Reservations;
by
[XmlElement("Reservations")]
Reservation [] Reservations;
and then use the XmlSerializer

Related

Xml deserialize array to list

I have following xml
<result>
<key accessMask="4294967295" type="Account" expires="">
<rowset name="characters" key="characterID" columns="characterID,characterName,corporationID,corporationName,allianceID,allianceName,factionID,factionName">
<row characterID="123" characterName="Sefa 123" corporationID="456" corporationName="Signal Cartel" allianceID="159" allianceName="Scouts" factionID="0" factionName=""/>
<row characterID="1234" characterName="Sefa 1234" corporationID="987" corporationName="Havos" allianceID="753" allianceName="Unlimited" factionID="0" factionName=""/>
</rowset>
</key>
</result>
And i have following Schema setup for deserializing this output.
[XmlRoot("result")]
public class ApiKeyInfo
{
[XmlElement("key")]
public Key Key { get; set; }
}
public class Key
{
[XmlAttribute("accessMask")]
public long AccessMask { get; set; }
[XmlAttribute("type")]
public string Type { get; set; }
[XmlElement("rowset")]
public List<AccountCharacter> Characters { get; set; }
}
public class AccountCharacter
{
[XmlAttribute("characterId")]
public long Id { get; set; }
[XmlAttribute("characterName")]
public string Name { get; set; }
[XmlAttribute("corporationID")]
public long CorpId { get; set; }
[XmlAttribute("corporationName")]
public string CorpName { get; set; }
[XmlAttribute("allianceID")]
public long AllianceId { get; set; }
[XmlAttribute("allianceName")]
public string AllianceName { get; set; }
[XmlAttribute("factionID")]
public long FactionId { get; set; }
[XmlAttribute("factionName")]
public string FactionName { get; set; }
}
Problem is, i can't deserialize character informations. Characters list is always containing 0 elements inside.
This:
[XmlElement("rowset")]
public List<AccountCharacter> Characters { get; set; }
Implies that you'll have a bunch of rowset elements, e.g:
<rowset characterID="123" characterName="Sefa 123" ...
Try this instead:
[XmlArray("rowset")]
[XmlArrayItem("row")]
public List<AccountCharacter> Characters { get; set; }
A useful tip for these sort of deserialisation problems is to try the process in reverse: create an object and serialise it and see what the XML looks like. It will likely give you some indication as to where your problem is.
See this fiddle for a working demo, it prints both row name values to the console.

XML Deserializing returns "some" null values

Here's my XML:
<Events>
<Event>
<content_id>6442452774</content_id>
<content_title>Title of the event</content_title>
<content_html>
<Date>2015-11-18</Date>
<EventType>Events</EventType>
<Description>
<p>this is an "event"</p>
</Description>
<Speakers>speaker1 LLC<br />speaker2<br />Jspeaker3</Speakers>
<Time>5:30 - 6:00pm Registration<br />6:00 - 7:00pm Panel Discussion<br />7:00 - 8:00pm Networking Reception</Time>
<Where></Where>
<RegistrationInfo>Please contact events#events.com to register for this event.</RegistrationInfo>
<Registration>false</Registration>
</content_html>
<date_created>2015-10-24T14:24:12.333</date_created>
<folder_id>262</folder_id>
<content_teaser>this is the content "can you display it."</content_teaser>
<content_text>text of the vent "more text" a lot of text here </content_text>
<end_date>2015-11-19T21:35:00</end_date>
<content_type>1</content_type>
<template_id>43</template_id>
<content_status>A</content_status>
</Event>
<Event>.... Other events </Event>
<Events>
and here's are my classes:
public class Serializable_Events
{
[XmlElement("Event")]
public List<Serializable_Event> EventList = new List<Serializable_Event>();
}
public class Serializable_Event
{
[XmlElement("content_id")]
public string content_id { get; set; }
[XmlElement("content_title")]
public string content_title { get; set; }
[XmlElement("content_html")]
public Serializable_Event_ContentHTML ContentHTML { get; set; }
[XmlText]
public string content_teaser { get; set; }
[XmlElement("content_text")]
public string content_text { get; set; }
}
public class Serializable_Event_ContentHTML
{
[XmlElement("Date")]
public string Date { get; set; }
[XmlElement("EventType")]
public string EventType { get; set; }
[XmlElement("Description")]
public string Description { get; set; }
[XmlElement("Speakers")]
public string Speakers { get; set; }
[XmlElement("Time")]
public string Time { get; set; }
[XmlElement("Where")]
public string Where { get; set; }
[XmlElement("RegistrationInfo")]
public string RegistrationInfo { get; set; }
[XmlElement("Registration")]
public bool Registration { get; set; }
//ignored html tags
[XmlIgnore]
public string p { get; set; }
[XmlIgnore]
public string br { get; set; }
[XmlIgnore]
public string a { get; set; }
}
Implementation:
XmlSerializer ser = new XmlSerializer(typeof(Serializable_Events));
var data = (Serializable_Events)ser.Deserialize(new StreamReader(#"events.xml"));
My problem is that some attributes are null and some are not (see the screenshot)
The ones that are null, like <Description> are due to malformed
XML.
You are storing HMTL directly in XML with text all over the place, and the serializer is not expecting that; further you are telling the serializer to ignore HTML tags using XmlIgnore which is intended for XML tags with properly formed XML. That's a wrong use of XmlIgnore
All XML which contains non-XML mark-up should be wrapped in CDATA sections; this will solve your problem. Further, you can remove all of the XmlIgnore code as well since it's not needed.
Your XML should look like this:
<Events>
<Event>
<content_id>6442452774</content_id>
<content_title>Title of the event</content_title>
<content_html>
<Date>2015-11-18</Date>
<EventType>Events</EventType>
<Description>
<![CDATA[<p>this is an ""event""</p>]]>
</Description>
<Speakers>
<![CDATA[speaker1 LLC<br />speaker2<br />Jspeaker3]]>
</Speakers>
<Time>
<![CDATA[5:30 - 6:00pm Registration<br />6:00 - 7:00pm Panel Discussion<br />7:00 - 8:00pm Networking Reception]]>
</Time>
<Where></Where>
<RegistrationInfo>
<![CDATA[Please contact <a href='mailto:events#events.com'>events#events.com</a> to register for this event.]]>
</RegistrationInfo>
<Registration>false</Registration>
</content_html>
<date_created>2015-10-24T14:24:12.333</date_created>
<folder_id>262</folder_id>
<content_teaser>this is the content 'can you display it.'</content_teaser>
<content_text>text of the vent 'more text' a lot of text here </content_text>
<end_date>2015-11-19T21:35:00</end_date>
<content_type>1</content_type>
<template_id>43</template_id>
<content_status>A</content_status>
</Event>
</Events>"

Xml Serialization for list Property doesn't work when one item in the list

<TotalRecords ItineraryCount='1' >
<Recs ItineraryNumber="1" >
<Amount>516.6</Amount>
<TravelTime>940</TravelTime>
<FSegment>
<OutProperty>
<Segment No="1">
<Name>Ronald</Name>
<City>London</City>
<Country>United Kingdom</Country>
</Segment>
<Segment No="2">
<Name>Richard</Name>
<City>
London
</City>
<Country>United Kingdom</Country>
</Segment>
</OutProperty>
</FSegment>
</Recs>
</TotalRecords >
I am serializing xml to object of TotalRecords Class. It works fine when there are more than one segment in the OutProperty but in case of one segment it doesn't serialize into list property.
I have also tried with [XmlArray("")] and [XMlArrayItem("")] but it doesn't work. Anyone have idea?
public class TotalRecords
{
public Recs recs { get; set; }
public string ItineraryCount { get; set; }
}
public partial class Recs
{
public string amountField { get; set; }
public string travelTimeField { get; set; }
public FSegment fSegmentField { get; set; }
public string itineraryNumberField { get; set; }
}
public class FSegment
{
public List<Segment> OutProperty {get;set;}
}
public class Segment
{
public string nameField { get; set; }
public string cityField { get; set; }
public string countryField { get; set; }
}
Try to use the following for your Classes and their Properties:
[DataContract]
public class Contact
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
}
Hacking like this helps in many cases, perhaps in your too (converting List to array):
public class FSegment
{
[XmlIgnore]
public List<Segment> OutProperty {get;set;}
[XmlArray("OutProperty");
public Segment[] _OutProperty
{
get { return OutProperty.ToArray(); }
set { OutProperty = new List<Segment>(value); }
}
}
I am not exactly sure how your provided class definition worked previously without any XML attribute/element definitions since your variable names are not the same as the XML identifiers, meaning that the serialization wouldn't populate the properties that it couldn't find a name for.
Nether the less, the main issue here is that you are trying to put a list into a normal property.
From the XML provided, OutProperty is a single sub element of FSegment and Segment is an array of sub elements of OutProperty, but in your provided code, you tried to make Segment an array sub element of FSegment.
The correct structure of the class definition should be as follows (also including the XML definitions)
[System.Xml.Serialization.XmlRoot(ElementName="TotalRecords")]
public class TotalRecords
{
[System.Xml.Serialization.XmlElement(ElementName="Recs")]
public Recs recs { get; set; }
[System.Xml.Serialization.XmlAttribute(AttributeName = "ItineraryCount")]
public string ItineraryCount { get; set; }
}
public partial class Recs
{
[System.Xml.Serialization.XmlElement(ElementName = "Amount")]
public string amountField { get; set; }
[System.Xml.Serialization.XmlElement(ElementName = "TravelTime")]
public string travelTimeField { get; set; }
[System.Xml.Serialization.XmlElement(ElementName = "FSegment")]
public FSegment fSegmentField { get; set; }
[System.Xml.Serialization.XmlAttribute(AttributeName = "ItineraryNumber")]
public string itineraryNumberField { get; set; }
}
public class FSegment
{
[System.Xml.Serialization.XmlElement(ElementName = "OutProperty")]
public SegmentList OutProperty { get; set; }
}
public class SegmentList
{
[System.Xml.Serialization.XmlElement(ElementName = "Segment")]
public List<Segment> segmentField { get; set; }
}
public class Segment
{
[System.Xml.Serialization.XmlElement(ElementName = "Name")]
public string nameField { get; set; }
[System.Xml.Serialization.XmlElement(ElementName = "City")]
public string cityField { get; set; }
[System.Xml.Serialization.XmlElement(ElementName = "Country")]
public string countryField { get; set; }
[System.Xml.Serialization.XmlAttribute(AttributeName = "No")]
public int segmentNoField { get; set; }
}
Please note that in the above structure, Segment is a list object under the OutProperty object, which resides under the FSegment object.
Using this class structure to load your XML produces the (assumed) correct data in the created objects.
Using the XML definitions allows you to decouple the actual names of class properties from what they are called in the XML data. This allows you to changes the one or the other without affecting the other one, which is useful when you don't control the creation of the XML data.
If you don't want all the XML definitions in your code, change the names of the classes so that you can name your properties the same as what they are called in the XML file. That will allow you couple everything directly

Xml Deserialize returms null values but xml has values

I saw few topics but no one looks like my problem.
Here is my class:
namespace Framework.Cielo.Models
{
[XmlRoot("transacao", Namespace = "http://ecommerce.cbmp.com.br")]
public class TransactionResponse
{
[XmlAttribute("id")]
public string ID { get; set; }
[XmlAttribute("versao")]
public string Version { get; set; }
[XmlElement("tid")]
public string tid { get; set; }
[XmlElement("pan")]
public string pan { get; set; }
[XmlElement("dados-pedido")]
public EstablishmentOrder Order { get; set; }
[XmlElement("forma-pagamento")]
public PaymentMethod PaymentMethod { get; set; }
[XmlElement("status")]
public TransactionStatusEnum Status { get; set; }
[XmlElement("url-retorno")]
public string ReturnUrl { get; set; }
[XmlElement("autenticacao")]
public Authentication Authentication { get; set; }
}
}
and here is the authentication class
namespace Framework.Cielo.Models
{
[XmlRoot("autenticacao")]
public class Authentication
{
[XmlElement("codigo")]
public int Code { get; set; }
[XmlElement("mensagem")]
public string Message { get; set; }
[XmlIgnore]
public DateTime Date { get; set; }
[XmlElement("data-hora")]
public string FormattedDate
{
get
{
return Date.ToString("yyyy-MM-ddTHH:mm:ss");
}
set
{
DateTime kdc = DateTime.MinValue;
DateTime.TryParse(value, out kdc);
Date = kdc;
}
}
[XmlElement("valor")]
public int Value { get; set; }
[XmlElement("lr")]
public int SecurityLevel { get; set; }
[XmlElement("arp")]
public object arp { get; set; }
[XmlElement("nsu")]
public object nsu { get; set; }
}
}
Here is how I deserialize:
string serializado = File.ReadAllText("req.xml");
var stringReader = new System.IO.StringReader(serializado);
var serializer = new XmlSerializer(typeof(TransactionResponse));
TransactionResponse preAuthResponse = serializer.Deserialize(stringReader) as TransactionResponse;
and here is my XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<transacao versao="1.3.0" id="100" xmlns="http://ecommerce.cbmp.com.br">
<tid>10069930690A16DF1001</tid>
<pan>b1SQ6jpKCDt3n9C0dgD/ZkPQ1Bh+7aJESqr/CwP64P0=</pan>
<dados-pedido>
<numero>100</numero>
<valor>29900</valor>
<moeda>986</moeda>
<data-hora>2013-10-15T00:57:19.032-03:00</data-hora>
<descricao/>
<idioma>PT</idioma>
<taxa-embarque>0</taxa-embarque>
</dados-pedido>
<forma-pagamento>
<bandeira>mastercard</bandeira>
<produto>1</produto>
<parcelas>1</parcelas>
</forma-pagamento>
<status>4</status>
<autenticacao>
<codigo>4</codigo>
<mensagem>Transacao sem autenticacao</mensagem>
<data-hora>2013-10-15T00:57:19.037-03:00</data-hora>
<valor>29900</valor>
<eci>0</eci>
</autenticacao>
<autorizacao>
<codigo>4</codigo>
<mensagem>Transação autorizada</mensagem>
<data-hora>2013-10-15T00:57:19.041-03:00</data-hora>
<valor>29900</valor>
<lr>00</lr>
<arp>123456</arp>
<nsu>661215</nsu>
</autorizacao>
</transacao>
When I run this code, all the elements get right, but not ARP and NSU elements (the last 2 of autorizacao tag)
I really don't know why. This XML comes from a web service and I can't figure out why my deserialize don't work with the 2 last items but works greater with any other element.
I have tried with your code and updated following and it works.
Commented second last <autenticacao> tag.
Rename last tag <autorizacao> to <autenticacao> . May be you are getting wrong xml & last two tags are confusing so I have tried with only one tag.
In Authentication class I have changed type of ARP and NSU otherwise we are getting XMlNode type while deserializing. You can also use string instead of int.
[XmlElement("arp")]
public int arp { get; set; }
[XmlElement("nsu")]
public int nsu { get; set; }

Deserializing xml element to Array with XmlSerializer doesn't work

I want to deserialize the following xml into my class, i can't change the xml because it commes from a device over tcp/ip.
<?xml version="1.0" encoding="utf-8"?>
<CONTACTINFORMATION UID="1234">
<LoginId><![CDATA[1234]]></LoginId>
<ContactId><![CDATA[2134]]></ContactId>
<ContactType>CCININTERN</ContactType>
<Status>CONVERSATION</Status>
<From><![CDATA[123]]></From>
<To><![CDATA[123]]></To>
<WaitTime><![CDATA[123]]></WaitTime>
<ContactPropertySummary>
<ContactProperty>
<Name><![CDATA[13]]></Name>
<Value><![CDATA[13]]></Value>
<Hidden>NO</Hidden>
<Url><![CDATA[13]]></Url>
</ContactProperty>
</ContactPropertySummary>
<SkillSummary>
<Skill>
<Name><![CDATA[123]]></Name>
<Mandatory>YES</Mandatory>
</Skill>
<Skill>
<Name><![CDATA[124]]></Name>
<Mandatory>YES</Mandatory>
</Skill>
</SkillSummary>
<ContactCodeSummary>
<ContactCode>
<Id>123</Id>
<Hidden>NO</Hidden>
<Assigned>YES</Assigned>
</ContactCode>
</ContactCodeSummary>
<GroupSummary>
<Group>
<Name><![CDATA[123]]></Name>
<Mandatory>YES</Mandatory>
</Group>
</GroupSummary>
<PreviousAgent><![CDATA[2]]></PreviousAgent>
<ScratchPadId><![CDATA[2]]></ScratchPadId>
<ScratchPadData><![CDATA[2]]></ScratchPadData>
<FaxSpecific>
<NbrOfPages>2</NbrOfPages>
</FaxSpecific>
</CONTACTINFORMATION>
My class:
[Serializable]
[XmlRoot("CONTACTINFORMATION")]
public class Contact
{
#region :: PROPERTIES ::
public string LoginId { get; set; }
public string ContactId { get; set; }
public ContactType ContactType { get; set; }
public ContactStatus Status { get; set; }
[XmlElement("From")]
public string ContactFrom { get; set; }
[XmlElement("To")]
public string ContactTo { get; set; }
public int WaitTime { get; set; }
[XmlElement("SkillSummary", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlArray("Skill")]
//[XmlElement("SkillSummary", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Skill[] Skills { get; set; }
[XmlArray("ContactPropertySummary")]
public ContactProperty[] Properties { get; set; }
[XmlArray("GroupSummary", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlArrayItem("Group", typeof(Group), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Group[] Groups { get; set; }
}
The arry of skills has 2 skills, after deserializing there is only 1 skill in the arry, the groups and properties array is null...
What i'm doing wrong?
You should properly decorate array properties with XmlArray and XmlArrayItem attributes. For e.g. for skills property you are using XmlElement with XmlArray which is not permitted.
[XmlArrayItem("Skill", typeof(Skill), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlArray("SkillSummary", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Skill[] Skills
{
get;
set;
}
[XmlArray("ContactPropertySummary")]
[XmlArrayItem("ContactProperty", typeof(ContactProperty), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public ContactProperty[] Properties
{
get;
set;
}
[XmlArray("GroupSummary", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlArrayItem("Group", typeof(Group), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public Group[] Groups
{
get;
set;
}
Make Sure that xmlArrayItem 'types' have proper read/write properties
public class Skill
{
public string Name
{
get;
set;
}
public string Mandatory
{
get;
set;
}
}
I recommend you to provide as much information to the XMLSerializer, through attributes, as you can.
You don't seem to be too off the mark. Using the above definitions I was able to successfully deserialize the XML you provided.
Start by defining a class Skill and then using this class in your Contract class.
// We're going to define a class called Skill
[Serializable()]
public class Skill
{
[System.Xml.Serialization.XmlElement("Name")]
public string Name { get; set; }
[System.Xml.Serialization.XmlElement("Mandatory")]
public string Mandatory { get; set; }
}
[Serializable]
[XmlRoot("CONTACTINFORMATION")]
public class Contact
{
// ...... Rest of your elements
[XmlArray("SkillSummary")]
[XmlArrayItem("Skill", typeof(Skill))]
public Skills[] Skill { get; set; }
}
Please do the same for Groups and Properties as well.

Categories