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.
Related
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; }
}
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.
<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
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; }
I have XML-based config for application shortcuts bindings. i need to parse it.
<ShortcutBinding>
<ShortcutHandler Name ="Retail.Application.Documents.Outcome.Presentation.OutcomePresenter">
<Shortcut Name="EditHeader">
<Key>CTRL</Key>
<Key>F4</Key>
</Shortcut>
<Shortcut Name="EditItem">
<Key>F4</Key>
</Shortcut>
</ShortcutHandler>
</ShortcutBinding>
I know that .Net has attributes for deserializing XML into objects.
Can anyone write complete example for such deserialization, using attributes.
public class ShortcutBinding
{
public ShortcutHandler ShortcutHandler { get; set; }
}
public class ShortcutHandler
{
[XmlAttribute]
public string Name { get; set; }
[XmlElement("Shortcut")]
public List<Shortcut> Shortcuts { get; set; }
}
public class Shortcut
{
[XmlAttribute]
public string Name { get; set; }
[XmlElement("Key")]
public List<string> Keys { get; set; }
}
Deserializing:
XmlSerializer serializer = new XmlSerializer(typeof(ShortcutBinding));
var binding = (ShortcutBinding)serializer.Deserialize(XmlReader.Create(path));