Deserialize an xml not extract the object - c#

I want to deserialize an XML string to an object. the execution don't return an error or an exception. I search in net but don't find any solution that I can apply to my issue.
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Get_mouvements_usersResult";
xRoot.Namespace = "urn:DME_Webservices";
xRoot.IsNullable = false;
trueObject="<ns1:Get_mouvements_usersResult xmlns:ns1=\"urn:DME_Webservices\"><Obj_info_retour><flag_erreur>false</flag_erreur><libelle_erreur/><libelle_detail_erreur/></Obj_info_retour><tab_Cuser_mouvements><obj_cuser><IPP>02084</IPP><Id_user>4503843842</Id_user><civilite>Mme</civilite><nom_usuel>BOTTU</nom_usuel><nom_naissance>LOACU</nom_naissance><prenom>Alida</prenom><date_naissance>19340707</date_naissance><numro_sejour>31202084001</numro_sejour><date_deb_sejour>20150420113700</date_deb_sejour><code_lit>504</code_lit><code_etablissement>000312</code_etablissement></obj_cuser><tab_obj_Cmouvement>Id_mouvement>4505631384</Id_mouvement><date_mouvement>20150420113700</date_mouvement><code_mouvement>E</code_mouvement><Libelle_mouvement>Entre tablissement</Libelle_mouvement><code_ufh>ETG1</code_ufh><libelle_ufh>Etage 1-Chteau de Fermaincourt</libelle_ufh><code_ufm>SSR_HC_CONVA</code_ufm><libelle_ufm>Convalescence</libelle_ufm><Date_fin_mouvement>20150422152600</Date_fin_mouvement><code_lit>402</code_lit><comm_mouvement/>/tab_obj_Cmouvement><tab_obj_Cmouvement><Id_mouvement>4533166359</Id_mouvement><date_mouvement>20150422152600</date_mouvement><code_mouvement>M</code_mouvement><Libelle_mouvement>Mutation</Libelle_mouvement>code_ufh>ETG3</code_ufh><libelle_ufh>Etage 3 - La Chapelle Royale</libelle_ufh><code_ufm>SSR_HC_CONVA</code_ufm><libelle_ufm>Convalescence</libelle_ufm><Date_fin_mouvement>20150730142100</Date_fin_mouvement>code_lit>605D</code_lit><comm_mouvement/></tab_obj_Cmouvement><tab_obj_Cmouvement><Id_mouvement>5125097053</Id_mouvement><date_mouvement>20150730142100</date_mouvement><code_mouvement>M</code_mouvement><Libelle_mouvement>Mutation</Libelle_mouvement><code_ufh>ETG2</code_ufh><libelle_ufh>Etage 2 - Domaine de Comteville</libelle_ufh><code_ufm>SSR_HC_SDSG</code_ufm><libelle_ufm>Griatrie</libelle_ufm><Date_fin_mouvement/><code_lit>504</code_lit><comm_mouvement/></tab_obj_Cmouvement></tab_Cuser_mouvements></ns1:Get_mouvements_usersResult>";
MemoryStream stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(trueObject));
XmlSerializer serializer = new XmlSerializer(typeof(XmlUsers), xRoot);
listXmlUserMove = (XmlUsers)serializer.Deserialize(stream);
I have these classes:
[Serializable, XmlRoot("ns1:Get_mouvements_usersResult"), XmlType("ns1:Get_mouvements_usersResult")]
public class XmlUsers
{
[XmlElement("tab_Cuser_mouvements")]
public List<XmlUserMove> UserList { get; set; }
[XmlElement("Obj_info_retour")]
public SoapResult soapResult { get; set; }
}
[XmlType("Obj_info_retour")]
public class SoapResult
{
[XmlElement("flag_erreur")]
public string ErrorFlag { get; set; }
[XmlElement("libelle_erreur")]
public string ErrorName { get; set; }
[XmlElement("libelle_detail_erreur")]
public string ErrorDetails { get; set; }
}
[XmlType("tab_Cuser_mouvements")]
public class XmlUserMove
{
[XmlElement("obj_cuser")]
public XmlUser user { get; set; }
[XmlElement("tab_obj_Cmouvement")]
public List<XmlMove> MoveList { get; set; }
}
public class XmlUser
{
[XmlElementAttribute("IPP")]
public string IPP { get; set; }
[XmlElementAttribute("Id_patient")]
public string IdUser { get; set; }
[XmlElementAttribute("civilite")]
public string Title { get; set; }
[XmlElementAttribute("nom_usuel")]
public string UsedLastName { get; set; }
[XmlElementAttribute("nom_naissance")]
public string BirthLastName { get; set; }
[XmlElementAttribute("prenom")]
public string FirstName { get; set; }
[XmlElementAttribute("date_naissance")]
public string Birthday { get; set; }
[XmlElementAttribute("numero_sejour")]
public string RoomNumber { get; set; }
[XmlElementAttribute("date_deb_sejour")]
public string EntredDate { get; set; }
[XmlElementAttribute("code_lit")]
public string BedCode { get; set; }
[XmlElementAttribute("code_etablissement")]
public string DivisionCode { get; set; }
}
public class XmlMove
{
[XmlElement("Id_mouvement")]
public string MoveId { get; set; }
[XmlElement("date_mouvement")]
public string MoveDate { get; set; }
[XmlElement("code_mouvement")]
public string MoveCode { get; set; }
[XmlElement("Libelle_mouvement")]
public string MoveName { get; set; }
[XmlElement("code_ufh")]
public string ufhCode { get; set; }
[XmlElement("libelle_ufh")]
public string UfhName { get; set; }
[XmlElement("code_ufm")]
public string UfmCode { get; set; }
[XmlElement("libelle_ufm")]
public string UfmName { get; set; }
[XmlElement("Date_fin_mouvement")]
public string MoveEndDate { get; set; }
[XmlElement("code_lit")]
public string BedCode { get; set; }
[XmlElement("comm_mouvement")]
public string MoveComm { get; set; }
}
The listXmlUserMove object don't contain anything but the xml contain many things.
Any one can help me please?

There are a few < characters missing from your trueObject, and you didn't include the XmlUser class, but since you reported an empty object and not an exception, I'm assuming what you have is really ok, and that was just a copy/paste error.
You don't need to declare the xRoot object separately if you get the attributes on XmlUsers set up correctly. ns1 is meaningless without context. You should use the Namespace property to give the info to those attributes correctly.
[Serializable, XmlRoot("Get_mouvements_usersResult", Namespace = "urn:DME_Webservices"), XmlType("Get_mouvements_usersResult", Namespace = "urn:DME_Webservices")]
public class XmlUsers
Your elements aren't coming through because of a namespace issue. XmlUsers's Namespace is assumed to apply to the elements inside of it. In your actual XML, though, they are in a different namespace. Since they have no xmlns defined, they're in the default namespace, an empty string. The element's namespaces should be set explicitly:
[Serializable, XmlRoot("Get_mouvements_usersResult", Namespace = "urn:DME_Webservices"), XmlType("Get_mouvements_usersResult", Namespace = "urn:DME_Webservices")]
public class XmlUsers
{
[XmlElement("tab_Cuser_mouvements", Namespace = "")]
public List<XmlUserMove> UserList { get; set; }
[XmlElement("Obj_info_retour", Namespace = "")]
public SoapResult soapResult { get; set; }
}
If you had intended everything to be inside ns1, then you'll need to rework your XML files and classes to match that.
So now the code to deserialize looks like this (note, this includes my fixed trueObject string)
var trueObject="<ns1:Get_mouvements_usersResult xmlns:ns1=\"urn:DME_Webservices\"><Obj_info_retour><flag_erreur>false</flag_erreur><libelle_erreur/><libelle_detail_erreur/></Obj_info_retour><tab_Cuser_mouvements><obj_cuser><IPP>02084</IPP><Id_user>4503843842</Id_user><civilite>Mme</civilite><nom_usuel>BOTTU</nom_usuel><nom_naissance>LOACU</nom_naissance><prenom>Alida</prenom><date_naissance>19340707</date_naissance><numro_sejour>31202084001</numro_sejour><date_deb_sejour>20150420113700</date_deb_sejour><code_lit>504</code_lit><code_etablissement>000312</code_etablissement></obj_cuser><tab_obj_Cmouvement><Id_mouvement>4505631384</Id_mouvement><date_mouvement>20150420113700</date_mouvement><code_mouvement>E</code_mouvement><Libelle_mouvement>Entre tablissement</Libelle_mouvement><code_ufh>ETG1</code_ufh><libelle_ufh>Etage 1-Chteau de Fermaincourt</libelle_ufh><code_ufm>SSR_HC_CONVA</code_ufm><libelle_ufm>Convalescence</libelle_ufm><Date_fin_mouvement>20150422152600</Date_fin_mouvement><code_lit>402</code_lit><comm_mouvement/></tab_obj_Cmouvement><tab_obj_Cmouvement><Id_mouvement>4533166359</Id_mouvement><date_mouvement>20150422152600</date_mouvement><code_mouvement>M</code_mouvement><Libelle_mouvement>Mutation</Libelle_mouvement><code_ufh>ETG3</code_ufh><libelle_ufh>Etage 3 - La Chapelle Royale</libelle_ufh><code_ufm>SSR_HC_CONVA</code_ufm><libelle_ufm>Convalescence</libelle_ufm><Date_fin_mouvement>20150730142100</Date_fin_mouvement><code_lit>605D</code_lit><comm_mouvement/></tab_obj_Cmouvement><tab_obj_Cmouvement><Id_mouvement>5125097053</Id_mouvement><date_mouvement>20150730142100</date_mouvement><code_mouvement>M</code_mouvement><Libelle_mouvement>Mutation</Libelle_mouvement><code_ufh>ETG2</code_ufh><libelle_ufh>Etage 2 - Domaine de Comteville</libelle_ufh><code_ufm>SSR_HC_SDSG</code_ufm><libelle_ufm>Griatrie</libelle_ufm><Date_fin_mouvement/><code_lit>504</code_lit><comm_mouvement/></tab_obj_Cmouvement></tab_Cuser_mouvements></ns1:Get_mouvements_usersResult>";
MemoryStream stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(trueObject));
XmlSerializer serializer = new XmlSerializer(typeof(XmlUsers));
var listXmlUserMove = (XmlUsers)serializer.Deserialize(stream);
But the object is actually populated at the end!

I do what Tim S. tell me but I don't remove the xRoot :
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Get_mouvements_usersResult";
xRoot.Namespace = "urn:DME_Webservices";
xRoot.IsNullable = false;
.
XmlSerializer serializer = new XmlSerializer(typeof(XmlUsers), xRoot);
Now the solution work fine.
Thank you for your help :)

Related

How to parse API data in XML?

I'm currently working on an application through WPF and wonder what's the better option in my case. I have a web based API that originally prints it's own XML and fills in the elements with it's data, but since this'll eventually be on a live server I thought it might seem a bit more convenient if the executable creates an XML file and parses API data into it.
If my option seems better, how do I write designated data to XML elements? I'm sorry if my question is a bit vague.
My JSON classes
[DataContract]
public class ShipmentDetails
{
[DataMember(Name="salutationCode")]
public string salutationCode { get; set; }
[DataMember(Name="firstName")]
public string firstName { get; set; }
[DataMember(Name="surName")]
public string surName { get; set; }
[DataMember(Name="streetName")]
public string streetName { get; set; }
[DataMember(Name="houseNumber")]
public string houseNumber { get; set; }
[DataMember(Name="zipCode")]
public string zipCode { get; set; }
[DataMember(Name="city")]
public string city { get; set; }
[DataMember(Name="countryCode")]
public string countryCode { get; set; }
[DataMember(Name="email")]
public string email { get; set; }
[DataMember(Name="language")]
public string language { get; set; }
}
[DataContract]
public class BillingDetails
{
[DataMember(Name="salutationCode")]
public string salutationCode { get; set; }
[DataMember(Name="firstName")]
public string firstName { get; set; }
[DataMember(Name="surName")]
public string surName { get; set; }
[DataMember(Name="streetName")]
public string streetName { get; set; }
[DataMember(Name="houseNumber")]
public string houseNumber { get; set; }
[DataMember(Name="zipCode")]
public string zipCode { get; set; }
[DataMember(Name="city")]
public string city { get; set; }
[DataMember(Name="countryCode")]
public string countryCode { get; set; }
[DataMember(Name="email")]
public string email { get; set; }
}
[DataContract]
public class CustomerDetails
{
[DataMember(Name="shipmentDetails")]
public ShipmentDetails shipmentDetails { get; set; }
[DataMember(Name="billingDetails")]
public BillingDetails billingDetails { get; set; }
}
[DataContract]
public class OrderItem
{
[DataMember(Name="orderItemId")]
public string orderItemId { get; set; }
[DataMember(Name="offerReference")]
public string offerReference { get; set; }
[DataMember(Name="ean")]
public string ean { get; set; }
[DataMember(Name="title")]
public string title { get; set; }
[DataMember(Name="quantity")]
public int quantity { get; set; }
[DataMember(Name="offerPrice")]
public double offerPrice { get; set; }
[DataMember(Name="offerId")]
public string offerId { get; set; }
[DataMember(Name="transactionFee")]
public double transactionFee { get; set; }
[DataMember(Name="latestDeliveryDate")]
public string latestDeliveryDate { get; set; }
[DataMember(Name="expiryDate")]
public string expiryDate { get; set; }
[DataMember(Name="offerCondition")]
public string offerCondition { get; set; }
[DataMember(Name="cancelRequest")]
public bool cancelRequest { get; set; }
[DataMember(Name="fulfilmentMethod")]
public string fulfilmentMethod { get; set; }
}
[DataContract]
public class Example
{
[DataMember(Name="orderId")]
public string orderId { get; set; }
[DataMember(Name="pickUpPoint")]
public bool pickUpPoint { get; set; }
[DataMember(Name="dateTimeOrderPlaced")]
public DateTime dateTimeOrderPlaced { get; set; }
[DataMember(Name="customerDetails")]
public CustomerDetails customerDetails { get; set; }
[DataMember(Name="orderItems")]
public IList<OrderItem> orderItems { get; set; }
}
My XML
using (XmlWriter writer = XmlWriter.Create("Orders.xml"))
{
writer.WriteStartElement("start");
writer.WriteElementString("customer_id", "935933");
writer.WriteStartElement("orders");
writer.WriteStartElement("order");
writer.WriteElementString("order_id", "");
writer.WriteElementString("order_ref", "");
writer.WriteElementString("order_dropshipment", "");
writer.WriteElementString("order_dlv_adr_name", "");
writer.WriteElementString("order_dlv_adr_street", "");
writer.WriteElementString("order_dlv_adr_housenr", "");
writer.WriteElementString("order_dlv_adr_zipcode", "");
writer.WriteElementString("order_dlv_adr_city", "");
writer.WriteElementString("order_dlv_adr_email", "");
writer.WriteElementString("order_dlv_adr_phone", "");
writer.WriteElementString("order_dlv_adr_country_isocode", "");
writer.WriteStartElement("orderrows");
writer.WriteStartElement("orderrow");
writer.WriteElementString("orderrow_sku", "");
writer.WriteElementString("orderrow_qty", "");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.Flush();
}
XML mapping in PHP
$order->addChild('order_id',$info['orderId']);
$order->addChild('order_ref',$info['orderId']);// order_ref is usually the same as the order_id
$order->addChild('order_dropshipment',"Y"); // Yes and No if there's no dropshipment needed
$order->addChild('order_dlv_adr_name',$info['customerDetails']['shipmentDetails']['firstName'].' '.$info['customerDetails']['shipmentDetails']['surName']);
$order->addChild('order_dlv_adr_street',$info['customerDetails']['shipmentDetails']['streetName']);
$order->addChild('order_dlv_adr_housenr',$info['customerDetails']['shipmentDetails']['houseNumber']);
$order->addChild('order_dlv_adr_zipcode',$info['customerDetails']['shipmentDetails']['zipCode']);
$order->addChild('order_dlv_adr_city',$info['customerDetails']['shipmentDetails']['city']);
$order->addChild('order_dlv_adr_email',COMPANY_EMAIL);
$order->addChild('order_dlv_adr_phone',COMPANY_PHONE);
$order->addChild('order_dlv_adr_country_isocode',$info['customerDetails']['shipmentDetails']['countryCode']);
Desired output
<start>
<customer_id>935933</customer_id>
<orders>
<order>
<order_id>11864523</order_id>
<order_ref>11864523</order_ref>
<order_dropshipment>Y</order_dropshipment>
<order_dlv_adr_name>Fred Bellens</order_dlv_adr_name>
<order_dlv_adr_street>Elisabetaelaan</order_dlv_adr_street>
<order_dlv_adr_housenr>2</order_dlv_adr_housenr>
<order_dlv_adr_zipcode>3200</order_dlv_adr_zipcode>
<order_dlv_adr_city>Aarschot</order_dlv_adr_city>
<order_dlv_adr_email>*our mail*</order_dlv_adr_email>
<order_dlv_adr_phone>077 396 814</order_dlv_adr_phone>
<order_dlv_adr_country_isocode>BE</order_dlv_adr_country_isocode>
<orderrows>
<orderrow>
<orderrow_sku>KA0 14315 21_122</orderrow_sku>
<orderrow_qty>1</orderrow_qty>
</orderrow>
</orderrows>
</order>
</orders>
</start>
There are several ways how you can achieve that desired XML.
Let me show you two different ways:
XElement
Instead of relying on the XmlWriter we can construct the desired structure with XElement.
In your case the initialization of the tree could look similar to this:
var order = //...;
var shipment = order.customerDetails.billingDetails;
var xml = new XElement("start",
new XElement("customer_id", 935933),
new XElement("orders",
new XElement("order",
new XElement("order_id", order.orderId),
new XElement("order_ref", order.orderId),
new XElement("order_dropshipment", "Y"),
new XElement("order_dlv_adr_name", $"{shipment.firstName} {shipment.surName}"),
new XElement("order_dlv_adr_street", shipment.streetName),
new XElement("order_dlv_adr_housenr", shipment.houseNumber),
new XElement("order_dlv_adr_zipcode", shipment.zipCode),
new XElement("order_dlv_adr_city", shipment.city),
new XElement("order_dlv_adr_email", "TBD"),
new XElement("order_dlv_adr_phone", "TBD"),
new XElement("order_dlv_adr_country_isocode", shipment.countryCode)
)));
Then the persistence logic would look like this:
using var sampleXml = new FileStream("sample.xml", FileMode.CreateNew, FileAccess.Write);
using var fileWriter = new StreamWriter(sampleXml);
fileWriter.Write(xml.ToString());
fileWriter.Flush();
And that's it.
JsonConvert
As an alternative if you already have the desired structure in json then you can easily convert it to XML via JsonConvert's DeserializeXmlNode:
var orderInJson = JsonConvert.SerializeObject(data);
XmlDocument orderInXml = JsonConvert.DeserializeXmlNode(orderInJson);
And here is the persistence logic:
using var sampleXml = new XmlTextWriter("sample2.xml", Encoding.UTF8);
using var fileWriter = XmlWriter.Create(sampleXml);
orderInXml.WriteTo(fileWriter);
fileWriter.Flush();

XML not being serialised correctly into object

I am trying to serialise a piece of XML that is being returned from a third party API. However when doing so i am only retrieving part of the object upon serialisation. And only some of the values seem to exist. I thought this could be a input type problem, however all the types seem to be correct. I think it may have something to do with how my model is constructed.After debugging the code i have narrowed it down to be a problem with the conversion of the xml into the object.
C# CODE:
//[Route("api/AvailabiliyCheck/GetAvailability/{CSSDistrictCode}/{GoldAddressKey}")]
public EADAvailabilityDetails GetAvailabilityEAD([FromUri] string CSSDistrictCode, [FromUri] string GoldAddressKey)
{
//Load the request xml template
XmlDocument doc = new XmlDocument();
string path = HttpContext.Current.Server.MapPath("~/XML/Availability/GetAvailabilityEAD.xml");
doc.Load(path);
//Assign incoming paramaters to xml template
XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
manager.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/");
manager.AddNamespace("stupid_xmlns", "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService");
XmlNode CSSDistrictCodeNode = doc.SelectSingleNode("soap:Envelope/soap:Body/stupid_xmlns:GetAvailability/stupid_xmlns:request/stupid_xmlns:RequestDetails/stupid_xmlns:CSSDistrictCode", manager);
CSSDistrictCodeNode.InnerXml = CSSDistrictCode;
XmlNode GoldAddressKeyNode = doc.SelectSingleNode("soap:Envelope/soap:Body/stupid_xmlns:GetAvailability/stupid_xmlns:request/stupid_xmlns:RequestDetails/stupid_xmlns:GoldAddressKey", manager);
GoldAddressKeyNode.InnerXml = GoldAddressKey;
//Send Request To API
string _url = "https://b2b.api.talktalkgroup.com/api/v2/partners/AvailabilityCheckers/NPAC/v45";
string _action = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService/NetworkProductAvailabilityCheckerService/GetAvailability";
string xml = doc.InnerXml;
var soapResult = WebService.ApiRequest(_url, _action, xml);
XmlDocument xmlToFormat = new XmlDocument();
xmlToFormat.LoadXml(soapResult);
string Outerxml = xmlToFormat.FirstChild.FirstChild.FirstChild.FirstChild.ChildNodes[2].InnerXml;
//Remove all namespaces
var xmlToBeStripped = XElement.Parse(Outerxml);
string finalXml = XmlFormatter.stripNS(xmlToBeStripped).ToString();
EADAvailabilityDetails result;
// Deserialises xlm into an object
XmlSerializer serializer = new XmlSerializer(typeof(EADAvailabilityDetails));
using (TextReader reader = new StringReader(finalXml))
{
result = (EADAvailabilityDetails)serializer.Deserialize(reader);
}
return result;
}
XML being returned:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetAvailabilityResponse xmlns="http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService">
<GetAvailabilityResult xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Status xmlns="http://schemas.datacontract.org/2004/07/InHouse.SharedLibraries.ServiceBase.BaseTypes">
<Errors/>
<HasErrors>false</HasErrors>
</Status>
<CSSDistrictCode>lv</CSSDistrictCode>
<EADAvailability>
<AvailabilityDetails i:type="EADAvailabilityDetails">
<Status xmlns="http://schemas.datacontract.org/2004/07/InHouse.SharedLibraries.ServiceBase.BaseTypes">
<Errors/>
<HasErrors>false</HasErrors>
</Status>
<EADAvailability>
<EADAvailabilityResult>
<CollectorNodeExchangeCode>NDMAI</CollectorNodeExchangeCode>
<CollectorNodeExchangeName>Maidstone</CollectorNodeExchangeName>
<Distance>0</Distance>
<EADBandwidth xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>100M</a:string>
</EADBandwidth>
<EADSubType>EAD-LA</EADSubType>
<FibreExchangeCode>NDACO</FibreExchangeCode>
<FibreExchangename>Archers Court</FibreExchangename>
<IndicativeECC>Within tariff</IndicativeECC>
<IndicativeOrderCategory>Category 2.1</IndicativeOrderCategory>
<LocalExchangeCode>NDACO</LocalExchangeCode>
<LocalExchangeName>Archers Court</LocalExchangeName>
<ORLeadTime>40</ORLeadTime>
<OrderCategoryExplanation>There is a T node within 1km (or 650m in London) with spare capacity and ducting is in place, however some additional cabling is required between the premises and the T node.</OrderCategoryExplanation>
<TTLeadTime>56</TTLeadTime>
<Zone>0</Zone>
</EADAvailabilityResult>
<EADAvailabilityResult>
<CollectorNodeExchangeCode>NDMAI</CollectorNodeExchangeCode>
<CollectorNodeExchangeName>Maidstone</CollectorNodeExchangeName>
<Distance>0</Distance>
<EADBandwidth xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>LOW 1GB</a:string>
</EADBandwidth>
<EADSubType>EAD-LA</EADSubType>
<FibreExchangeCode>NDACO</FibreExchangeCode>
<FibreExchangename>Archers Court</FibreExchangename>
<IndicativeECC>Within tariff</IndicativeECC>
<IndicativeOrderCategory>Category 2.1</IndicativeOrderCategory>
<LocalExchangeCode>NDACO</LocalExchangeCode>
<LocalExchangeName>Archers Court</LocalExchangeName>
<ORLeadTime>40</ORLeadTime>
<OrderCategoryExplanation>There is a T node within 1km (or 650m in London) with spare capacity and ducting is in place, however some additional cabling is required between the premises and the T node.</OrderCategoryExplanation>
<TTLeadTime>56</TTLeadTime>
<Zone>0</Zone>
</EADAvailabilityResult>
<EADAvailabilityResult>
<CollectorNodeExchangeCode>NDCAN</CollectorNodeExchangeCode>
<CollectorNodeExchangeName>Canterbury</CollectorNodeExchangeName>
<Distance>20656</Distance>
<EADBandwidth xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<a:string>HIGH 1GB</a:string>
</EADBandwidth>
<EADSubType>EAD-NonLA</EADSubType>
<FibreExchangeCode>NDCAN</FibreExchangeCode>
<FibreExchangename>Canterbury</FibreExchangename>
<IndicativeECC>Within tariff</IndicativeECC>
<IndicativeOrderCategory>Category 2.1</IndicativeOrderCategory>
<LocalExchangeCode>NDACO</LocalExchangeCode>
<LocalExchangeName>Archers Court</LocalExchangeName>
<ORLeadTime>40</ORLeadTime>
<OrderCategoryExplanation>There is a T node within 1km (or 650m in London) with spare capacity and ducting is in place, however some additional cabling is required between the premises and the T node.</OrderCategoryExplanation>
<TTLeadTime>56</TTLeadTime>
<Zone>B</Zone>
</EADAvailabilityResult>
</EADAvailability>
<LeadTime>10</LeadTime>
</AvailabilityDetails>
</EADAvailability>
<GoldAddressKey>A00009292752</GoldAddressKey>
<Postcode/>
</GetAvailabilityResult>
</GetAvailabilityResponse>
</s:Body>
</s:Envelope>
Model:
[Serializable, XmlRoot("AvailabilityDetails")]
public class EADAvailabilityDetails
{
[XmlElement("EADAvailability")]
public EADAvailability EADAvailability { get; set; }
}
public class EADAvailability
{
[XmlElement("EADAvailabilityResult")]
public List<EADAvailabilityResult> EADAvailabilityResult { get; set; }
}
public class EADAvailabilityResult
{
[XmlElement("CollectorNodeExchangeCode")]
public string CollectorNodeExchangeCode { get; set; }
[XmlElement("CollectorNodeExchangeName")]
public string CollectorNodeExchangeName { get; set; }
[XmlElement("Distance")]
public int Distance { get; set; }
[XmlElement("EADBandwidth")]
public string EADBandwidth { get; set; }
[XmlElement("EADSubType")]
public string EADSubType { get; set; }
[XmlElement("FibreExchangeCode")]
public string FibreExchangeCode { get; set; }
[XmlElement("FibreExchangename")]
public string FibreExchangename { get; set; }
[XmlElement("IndicativeECC")]
public string IndicativeECC { get; set; }
[XmlElement("IndicativeOrderCategory")]
public string IndicativeOrderCategory { get; set; }
[XmlElement("LocalExchangeCode")]
public string LocalExchangeCode { get; set; }
[XmlElement("LocalExchangeName")]
public string LocalExchangeName { get; set; }
[XmlElement("ORLeadTime")]
public int ORLeadTime { get; set; }
[XmlElement("OrderCategoryExplanation")]
public string OrderCategoryExplanation { get; set; }
[XmlElement("TTLeadTime")]
public int TTLeadTime { get; set; }
[XmlElement("Zone")]
public int Zone { get; set; }
}
XML after serialisation:
{
"<EADAvailability>k__BackingField": {
"EADAvailabilityResult": [
{
"CollectorNodeExchangeCode": "NDMAI",
"CollectorNodeExchangeName": "Maidstone",
"Distance": 0,
"EADBandwidth": "100M",
"EADSubType": null,
"FibreExchangeCode": null,
"FibreExchangename": null,
"IndicativeECC": null,
"IndicativeOrderCategory": null,
"LocalExchangeCode": null,
"LocalExchangeName": null,
"ORLeadTime": 0,
"OrderCategoryExplanation": null,
"TTLeadTime": 0,
"Zone": 0
}
]
}
}
The code below works :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication139
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Envelope));
Envelope envelope = (Envelope)serializer.Deserialize(reader);
}
}
[XmlRoot(Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public class Envelope
{
[XmlElement (Namespace = "http://schemas.xmlsoap.org/soap/envelope/")]
public Body Body { get; set; }
}
public class Body
{
[XmlElement(Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public GetAvailabilityResponse GetAvailabilityResponse { get; set; }
}
public class GetAvailabilityResponse
{
[XmlElement(Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public GetAvailabilityResult GetAvailabilityResult { get; set; }
}
public class GetAvailabilityResult
{
[XmlArray("EADAvailability", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
[XmlArrayItem("AvailabilityDetails", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public AvailabilityDetails[] AvailabilityDetails { get; set; }
}
[XmlInclude(typeof(EADAvailabilityDetails))]
[Serializable, XmlRoot("AvailabilityDetails", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public class AvailabilityDetails
{
}
[Serializable, XmlRoot("EADAvailabilityDetails", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public class EADAvailabilityDetails : AvailabilityDetails
{
[XmlArray("EADAvailability", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
[XmlArrayItem("EADAvailabilityResult", Namespace = "http://webservices.talktalkplc.com/NetworkProductAvailabilityCheckerService")]
public EADAvailabilityResult[] EADAvailabilityResult { get; set; }
}
public class EADAvailabilityResult
{
public string CollectorNodeExchangeCode { get; set; }
public string CollectorNodeExchangeName { get; set; }
public int Distance { get; set; }
public EADBandwidth EADBandwidth { get; set; }
public string EADSubType { get; set; }
public string FibreExchangeCode { get; set; }
public string FibreExchangename { get; set; }
public string IndicativeECC { get; set; }
public string IndicativeOrderCategory { get; set; }
public string LocalExchangeCode { get; set; }
public string LocalExchangeName { get; set; }
public int ORLeadTime { get; set; }
public string OrderCategoryExplanation { get; set; }
public int TTLeadTime { get; set; }
public string Zone { get; set; }
}
public class EADBandwidth
{
[XmlElement(ElementName = "string", Type = typeof(string), Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")]
public string String { get; set; }
}
}

Null when trying to load a JSON from Root PCL Xamarin

Hi when trying to load a JSON file from the root of my PCL it breaks on this line Using (var reader = new StreamReader(stream)) and says its null.
here is the full method for loadJson()
public void LoadJson()
{
//Loads the JSON File in the Solution and Finds Correct ID of Accordion Hopefully!!
var assembly = typeof(App).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("MCETimeTest.TimeSheet.json");
string jsonString = "";
using (var reader = new StreamReader(stream))
{
jsonString = reader.ReadToEnd();
};
uoObj = JsonConvert.DeserializeObject<RootObject>(jsonString);
}
Edit: when stepping through the code stream is always null
and my classes for my json are:
//JSON Classes
public class RootObject
{
public List<LineItem> LineItems { get; set; }
}
public class Checks
{
public DateTime TheDate { get; set; }
public string JobNumber { get; set; }
public string CustomerName { get; set; }
public TimeSpan On1 { get; set; }
public TimeSpan Off1 { get; set; }
public TimeSpan On2 { get; set; }
public TimeSpan Off2 { get; set; }
public string Description { get; set; }
public string SingleHours { get; set; }
public string TimeHalfHours { get; set; }
public string DoubleHours { get; set; }
}
public class LineItem
{
public string Id { get; set; }
public string Customer { get; set; }
public List<Checks> Checks { get; set; }
}
Also looking over the solution it turns out that the JSON File in the root was not an Embedded Resource. After changing it, it works! sorry for the hassle!

Deserialize XML to object doesn't work

I have a XML as below. I want to convert this to c# object . I tried modyfying but could not get it working.
<SLVGeoZone-array>
<SLVGeoZone>
<id>19</id>
<type>geozone</type>
<name>60_OLC_SC</name>
<namesPath>GeoZones/60_OLC_SC</namesPath>
<idsPath>1/19</idsPath>
<childrenCount>0</childrenCount>
</SLVGeoZone>
</SLVGeoZone-array>
I have a written a sample c# code and it doesn't work:
[Serializable]
public class SLVGeoZone
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement("type")]
public string type { get; set; }
[XmlElement("name")]
public string name { get; set; }
[XmlElement("namespath")]
public string namespath { get; set; }
[XmlElement("idspath")]
public string idspath { get; set; }
[XmlElement("childrencount")]
public string childrencount { get; set; }
}
[Serializable]
[XmlRoot("SLVGeoZone-array")]
public class SLVGeoZone-array
{
[XmlArray("SLVGeoZone-array")]
[XmlArrayItem("SLVGeoZone", typeof(SLVGeoZone))]
public SLVGeoZone[] Car { get; set; }
}
And in the form:
XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));
StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();
Can someone suggest what am i doing wrong?
SLVGeoZone-array is not a valid class name in C#
[Serializable()]
[XmlRoot("SLVGeoZone-array")]
public class SLVGeoZones
{
[XmlElement("SLVGeoZone")]
public SLVGeoZone[] Cars { get; set; }
}
XmlElement attribute values have to be exactly the same as element names in XML file. Yours are not.
[Serializable()]
public class SLVGeoZone
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement("type")]
public string type { get; set; }
[XmlElement("name")]
public string name { get; set; }
[XmlElement("namesPath")]
public string namespath { get; set; }
[XmlElement("idsPath")]
public string idspath { get; set; }
[XmlElement("childrenCount")]
public string childrencount { get; set; }
}
What is CarCollection and why are you trying to deserialize your XML as CarCollection instead of classes you've shown here?
XmlSerializer serializer = new XmlSerializer(typeof(SLVGeoZones));
StreamReader reader = new StreamReader("Input.txt");
var items = (SLVGeoZones)serializer.Deserialize(reader);
reader.Close();

C# XMLNS complicated deserialization

I'm trying to deserialize XMLNS file.
<feed xmlns:live="http://www.live.com/marketplace" xmlns="http://www.w3.org/2005/Atom">
<live:totalItems>1177</live:totalItems>
<live:numItems>1</live:numItems>
<title>FindGames Results</title>
<updated>2013-09-19T09:28:02.77Z</updated>
<entry live:itemNum="34" live:detailView="3">
<id>urn:uuid:66ACD000-77FE-1000-9115-D802555308C3</id>
<updated>2013-09-19T09:28:02.77Z</updated>
<title>Rayman® Legends</title>
<content type="text">game content</content>
<live:media>
<live:mediaType>1</live:mediaType>
<live:gameTitleMediaId>urn:uuid:66ACD000-77FE-1000-9115-D802555308C3</live:gameTitleMediaId>
<live:reducedTitle>Rayman® Legends</live:reducedTitle>
<live:reducedDescription>The Glade of Dreams is in trouble once again! During a 100-year nap, nightmares have multiplied and spread, creating new monsters even scarier than before!</live:reducedDescription>
<live:availabilityDate>2013-06-11T00:00:00</live:availabilityDate>
<live:releaseDate>2013-08-29T00:00:00</live:releaseDate>
<live:ratingId>20</live:ratingId>
<live:developer>Ubisoft</live:developer>
<live:publisher>Ubisoft</live:publisher>
<live:newestOfferStartDate>2013-09-13T09:00:00Z</live:newestOfferStartDate>
<live:totalOfferCount>1</live:totalOfferCount>
<live:titleId>1431505091</live:titleId>
<live:effectiveTitleId>1431505091</live:effectiveTitleId>
<live:gameReducedTitle>Rayman® Legends</live:gameReducedTitle>
<live:ratingAggregate>4.50</live:ratingAggregate>
<live:numberOfRatings>1193</live:numberOfRatings>
</live:media>
</entry>
</feed>
My current code:
Deserialize class:
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class entry
{
public string title { get; set; }
public string totalItems { get; set; }
public string reducedDescription{ get; set; }
public string ratingId { get; set; }
public string developer { get; set; }
public string publisher { get; set; }
public string tittleId { get; set; }
public string ratingAggregate { get; set; }
public string numberOfRatings { get; set; }
public string boxImage { get; set; }
public string categories { get; set; }
}
class deserializeXML
{
public static void deserialize()
{
using (StreamReader reader = new StreamReader("Query.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(entry));
entry x1 = serializer.Deserialize(reader) as entry;
}
}
}
I just receiving title (FindGames Results instead of Rayman® Legends).
I need to get parameters after "entry" and "live:media", i have no idea how to receive parameters with "live:" at the beginning.
EDIT:
[XmlElement(Namespace = "http://www.live.com/marketplace")]
public int numItems { get; set; }
[XmlElement(Namespace = "http://www.live.com/marketplace")]
public int totalItems { get; set; }
It's working well, but:
[XmlElement("media" Namespace="http://www.live.com/marketplace")]
public media media{ get; set; }
This returning null media class :/
You need to explicitly map those types and properties that are not in the atom namespace to their respective namespaces. The namespace declaration in the XmlRoot just specifies the namespace of the root element. If you have multiple namespaces in the document you need to call them out explicitly.
For instance to map the itemNum attribute correctly try this in your entry class:
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class entry
{
[XmlAttribute("itemNum", Namespace = "http://www.live.com/marketplace")]
public int itemNum { get; set; }
public string title { get; set; }
public string totalItems { get; set; }
public string reducedDescription { get; set; }
public string ratingId { get; set; }
public string developer { get; set; }
public string publisher { get; set; }
public string tittleId { get; set; }
public string ratingAggregate { get; set; }
public string numberOfRatings { get; set; }
public string boxImage { get; set; }
public string categories { get; set; }
}
You then need to declare additional type to map into things like the media node.
class media
{
public int mediaType{ get; set; }
public string reducedDescription{ get; set; }
etc. etc.
}
You then need to move all of those "live" properties from your entry class into you new media class leaving you with an entry class that might look like this:
[XmlRoot("feed", Namespace = "http://www.w3.org/2005/Atom")]
public class entry
{
[XmlAttribute("itemNum", Namespace = "http://www.live.com/marketplace")]
public int itemNum { get; set; }
public string title { get; set; }
[XmlElement("media" Namespace="http://www.live.com/marketplace")]
public media media{ get; set; }
}
Your class hierarchy does not need to exactly match the xml hierarchy and you can do some significant remapping and transformation of the Xml using the various attributes in System.Xml.Serialization however I find it easier to implement, understand and maintain this sort of stuff if the C# classes map 1:1 onto the xml structure.

Categories