Xml deserialize array to list - c#

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.

Related

Creating XML Response in C#

I have created a REST Service which sends a response in XML. I have set the response format as XML and created the following Data Contracts:
[DataContract]
public class AuthorisationResult
{
[DataMember]
public string Status { get; set; }
[DataMember]
public Variable[] Variables { get; set; }
}
[DataContract]
public class Variable
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Type { get; set; }
}
This works ok however the output of the XML is not formatted as I need it. It is showing like this:
<Variables>
<Variable>
<Name>SomeName1</Name>
<Type>SomeType1</Type>
</Variable>
</Variables>
But I want to show it like this:
<Variables>
<Variable Name="SomeName1" Type="SomeType1"/>
</Variables>
Can anyone advise what I change to structure it how I want.
Just add XmlAttribute to the properties
[DataContract]
public class Variable
{
[DataMember, XmlAttribute]
public string Name { get; set; }
[DataMember, XmlAttribute]
public string Type { get; set; }
}

Deserializing XML with different Namespaces UWP

I have following XML-Data:
<?xml version="1.0"?>
<e:propertyset xmlns:e="urn:schemas-upnp-org:event-1-0">
<e:property>
<LastChange>
<Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/">
<InstanceID val="0">
<RoomVolumes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100"/>
<Volume channel="Master" val="100"/>
<Mute channel="Master" val="0"/>
<RoomMutes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0"/>
</InstanceID>
</Event>
</LastChange>
</e:property>
</e:propertyset>
And here are my classes:
[XmlRoot("propertyset", Namespace = "urn:schemas-upnp-org:event-1-0")]
public class EventPropertySet
{
[XmlElement("property")]
public List<EventProperty> Properties { get; set; }
}
public class EventProperty
{
[XmlElement("LastChange")]
public string LastChange { get; set; }
[XmlElement("SinkProtocolInfo")]
public string SinkProtocolInfo { get; set; }
[XmlElement("IndexerStatus")]
public string IndexerStatus { get; set; }
[XmlElement("SystemUpdateID")]
public string SystemUpdateID { get; set; }
}
Now when I try to deserialize the XML-Data 'LastChange' is always 'null'.
When I modify the class 'EventProperty' like so:
public class EventProperty
{
[XmlElement("LastChange", Namespae = "")]
public string LastChange { get; set; }
[XmlElement("SinkProtocolInfo", Namespae = "")]
public string SinkProtocolInfo { get; set; }
[XmlElement("IndexerStatus", Namespae = "")]
public string IndexerStatus { get; set; }
[XmlElement("SystemUpdateID", Namespae = "")]
public string SystemUpdateID { get; set; }
}
The deserialization throws an exception:
XmlException: ReadElementContentAs() methods cannot be called on an element that has child elements. Line 1, position 103.
Any ideas what I should do?
Sorry, I found the problem. The data behind "LastChange" is normaly a parsed XML-Structure (like this:)
<LastChange><Event xmlns="urn:schemas-upnp-org:metadata-1-0/RCS/"><InstanceID val="0"><RoomVolumes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=100"/><Volume channel="Master" val="100"/><Mute channel="Master" val="0"/><RoomMutes val="uuid:29e07ad9-224f-4160-a2bc-61d17845182a=0"/></InstanceID></Event></LastChange>
Now when I don't do the "DeParse" with WebUtility.HtmlDecode, everythings works fine.

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

Categories