I have this xml file:
<?xml version="1.0" encoding="UTF-8"?>
<pippo:Response xmlns:pippo="http://pippoonboarding.eu">
<pippo:Header>
<pippo:FileId>123</pippo:FileId>
<pippo:SenderId>1234</pippo:SenderId>
<pippo:ProcessingDate>20210630</pippo:ProcessingDate>
<pippo:ProcessingTime>1130</pippo:ProcessingTime>
<pippo:ResponseCode>OK</pippo:ResponseCode>
</pippo:Header>
<pippo:CompanyResponse>
<pippo:SellerId>1234</pippo:SellerId>
<pippo:SellerContractCode />
<pippo:VATNumber>123456</pippo:VATNumber>
<pippo:ResponseCode>KO</pippo:ResponseCode>
<pippo:PippoCompanyCode />
<pippo:ResponseDetails>
<pippo:Entity>ciaone</pippo:Entity>
<pippo:ProgressiveNumber>1</pippo:ProgressiveNumber>
<pippo:PippoShopCode />
<pippo:TerminalId />
<pippo:FieldName />
<pippo:ErrorType>DDD</pippo:ErrorType>
<pippo:ErrorCode>1234</pippo:ErrorCode>
<pippo:ErrorDescription>test</pippo:ErrorDescription>
</pippo:ResponseDetails>
</pippo:CompanyResponse>
</pippo:Response>
and I want to deserialize into my class:
public class XmlDeserializer
{
[Serializable, XmlRoot("pippo:Response xmlns:pippo=\"http://pippoonboarding.eu\"")]
public class Root
{
public string Response { get; set; }
//[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
public CompanyResponse CompanyResponse { get; set; }
}
public class Header
{
public string FileId { get; set; }
public string SenderId { get; set; }
public string ProcessingDate { get; set; }
public string ProcessingTime { get; set; }
public string ResponseCode { get; set; }
}
public class CompanyResponse
{
public string SellerId { get; set; }
public int SellerContractCode { get; set; }
public int VATNumber { get; set; }
public int ResponseCode { get; set; }
public int PippoCompanyCode { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Entity { get; set; }
public string ProgressiveNumber { get; set; }
public string PippoShopCode { get; set; }
public string TerminalId { get; set; }
public string FieldName { get; set; }
public string ErrorType { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
}
but I receive this error:
There is an error in XML document (2, 2).
<Response xmlns='http://pippoonboarding.eu'> was not expected.
What does the error mean? What should I do?
Following code works. Had to change a few integers to strings in class definitions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlDeserializer response = new XmlDeserializer(FILENAME);
}
}
public class XmlDeserializer
{
public XmlDeserializer(string filename)
{
XmlReader reader = XmlReader.Create(filename);
XmlSerializer serializer = new XmlSerializer(typeof(Root));
Root response = (Root)serializer.Deserialize(reader);
}
[XmlRoot(ElementName = "Response", Namespace = "http://pippoonboarding.eu")]
public class Root
{
public string Response { get; set; }
//[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
public CompanyResponse CompanyResponse { get; set; }
}
public class Header
{
public string FileId { get; set; }
public string SenderId { get; set; }
public string ProcessingDate { get; set; }
public string ProcessingTime { get; set; }
public string ResponseCode { get; set; }
}
public class CompanyResponse
{
public string SellerId { get; set; }
public string SellerContractCode { get; set; }
public int VATNumber { get; set; }
public string ResponseCode { get; set; }
public string PippoCompanyCode { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Entity { get; set; }
public string ProgressiveNumber { get; set; }
public string PippoShopCode { get; set; }
public string TerminalId { get; set; }
public string FieldName { get; set; }
public string ErrorType { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
}
}
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();
I have a xml item tag which should be mapped into List. But while mapping apart from the list of item other elements has been mapped to the model.
I referred to other questions where each items is given a parent so they mapped while deserialising.
Let me know how to map to the given list item into the respective model.
XML:
<SecretModel>
<id>3181</id>
<name>Test</name>
<secretTemplateId>6044</secretTemplateId>
<folderId>674</folderId>
<active>true</active>
<items>
<itemId>13960</itemId>
<fileAttachmentId/>
<filename/>
<itemValue>Test</itemValue>
<fieldId>287</fieldId>
<fieldName>Username</fieldName>
<slug>username</slug>
<fieldDescription>The Amazon IAM username.</fieldDescription>
<isFile>false</isFile>
<isNotes>false</isNotes>
<isPassword>false</isPassword>
</items>
<items>
<itemId>13961</itemId>
<fileAttachmentId/>
<filename/>
<itemValue>AKIAU5G4MQBA2TKQOWNW</itemValue>
<fieldId>284</fieldId>
<fieldName>Access Key</fieldName>
<slug>access-key</slug>
<fieldDescription>The Amazon IAM access key.</fieldDescription>
<isFile>false</isFile>
<isNotes>false</isNotes>
<isPassword>false</isPassword>
</items>
</secretModel>
SecretModel.cs:
Public class SecretModel
{
public int? id {get; set;}
public string name {get; set;}
public string SecretTemplateID {get; set;}
public string folderId {get; set;}
public string active {get; set;}
public string List<RestSecretItem> {get; set;}
}
public partial class RestSecretItem : IEquatable<RestSecretItem>
{
public string FieldDescription { get; set; }
public int? FieldId { get; set; }
public string FieldName { get; set; }
public int? FileAttachmentId { get; set; }
public string Filename { get; set; }
public bool? IsFile { get; set; }
public bool? IsNotes { get; set; }
public bool? IsPassword { get; set; }
public int? ItemId { get; set; }
public string ItemValue { get; set; }
public string Slug { get; set; }
}
There are many ways to map xml, one is using built-in .NET XML serializer. Here is one way to serialize it.
SecretModel
[XmlRoot(ElementName = "SecretModel")]
public class SecretModel
{
[XmlAttribute(AttributeName = "id")]
public int Id { get; set; }
[XmlAttribute(AttributeName = "name")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "secretTemplateId")]
public string SecretTemplateId { get; set; }
[XmlAttribute(AttributeName = "folderId")]
public string FolderId { get; set; }
[XmlAttribute(AttributeName = "active")]
public bool Active { get; set; }
[XmlElement(ElementName = "items")]
public List<RestSecretItem> Items { get; set; }
}
RestSecretItem
[XmlRoot(ElementName = "items")]
public class RestSecretItem
{
[XmlAttribute(AttributeName = "itemId")]
public int ItemId { get; set; }
[XmlAttribute(AttributeName = "fileAttachmentId")]
public int FileAttachmentId { get; set; }
[XmlAttribute(AttributeName = "filename")]
public string FileName { get; set; }
[XmlAttribute(AttributeName = "itemValue")]
public string ItemValue { get; set; }
[XmlAttribute(AttributeName = "fieldId")]
public int FieldId { get; set; }
[XmlAttribute(AttributeName = "fieldName")]
public string FieldName { get; set; }
[XmlAttribute(AttributeName = "slug")]
public string Slug { get; set; }
[XmlAttribute(AttributeName = "fieldDescription")]
public string FieldDescription { get; set; }
[XmlAttribute(AttributeName = "isFile")]
public bool IsFile { get; set; }
[XmlAttribute(AttributeName = "isNotes")]
public bool IsNote { get; set; }
[XmlAttribute(AttributeName = "isPassword")]
public bool IsPassword { get; set; }
}
Now you can parse the xml through using this code:
var doc = new XmlDocument();
doc.load("your directory or path of file here");
using(var reader = new StringReader(doc.InnerXml))
{
var serializer = new XmlSerializer(typeof(SecretModel));
var data = (SecretModel)serializer.Deserialize(reader); // converted model here
}
I am trying to deserialize an XML .
Sample XML is given below
<?xml version="1.0" ?>
<TRANSACTION_RESPONSE>
<TRANSACTION>
<TRANSACTION_ID>25429</TRANSACTION_ID>
<MERCHANT_ACC_NO>02700701354375000964</MERCHANT_ACC_NO>
<TXN_STATUS>F</TXN_STATUS>
<TXN_SIGNATURE>a16af68d4c3e2280e44bd7c2c23f2af6cb1f0e5a28c266ea741608e72b1a5e4224da5b975909cc43c53b6c0f7f1bbf0820269caa3e350dd1812484edc499b279</TXN_SIGNATURE>
<TXN_SIGNATURE2>B1684258EA112C8B5BA51F73CDA9864D1BB98E04F5A78B67A3E539BEF96CCF4D16CFF6B9E04818B50E855E0783BB075309D112CA596BDC49F9738C4BF3AA1FB4</TXN_SIGNATURE2>
<TRAN_DATE>29-09-2015 07:36:59</TRAN_DATE>
<MERCHANT_TRANID>150929093703RUDZMX4</MERCHANT_TRANID>
<RESPONSE_CODE>9967</RESPONSE_CODE>
<RESPONSE_DESC>Bank rejected transaction!</RESPONSE_DESC>
<CUSTOMER_ID>RUDZMX</CUSTOMER_ID>
<AUTH_ID />
<AUTH_DATE />
<CAPTURE_DATE />
<SALES_DATE />
<VOID_REV_DATE />
<REFUND_DATE />
<REFUND_AMOUNT>0.00</REFUND_AMOUNT>
</TRANSACTION>
</TRANSACTION_RESPONSE>
Following is the Class
[XmlType("TRANSACTION_RESPONSE")]
public class BankQueryResponse
{
[XmlElement("TRANSACTION_ID")]
public string TransactionId { get; set; }
[XmlElement("MERCHANT_ACC_NO")]
public string MerchantAccNo { get; set; }
[XmlElement("TXN_SIGNATURE")]
public string TxnSignature { get; set; }
[XmlElement("TRAN_DATE")]
public DateTime TranDate { get; set; }
[XmlElement("TXN_STATUS")]
public string TxnStatus { get; set; }
[XmlElement("REFUND_DATE")]
public DateTime RefundDate { get; set; }
[XmlElement("RESPONSE_CODE")]
public string ResponseCode { get; set; }
[XmlElement("RESPONSE_DESC")]
public string ResponseDesc { get; set; }
[XmlAttribute("MERCHANT_TRANID")]
public string MerchantTranId { get; set; }
}
The deserialization code is
BankQueryResponse result = new BankQueryResponse();
if(!string.IsNullOrEmpty(responseData))
{
XmlSerializer serializer = new XmlSerializer(typeof(BankQueryResponse));
using(TextReader xmlreader = new StringReader(responseData))
{
result = (BankQueryResponse) serializer.Deserialize(xmlreader);
}
}
I am getting all value in result as null . I am not sure whats the reason . Can some one throws a light into the issue. Am i missing something while deserialising
You should modify the code something like this
[XmlType("TRANSACTION_RESPONSE")]
public class TransactionResponse
{
[XmlElement("TRANSACTION")]
public BankQueryResponse Response { get; set; }
}
This will change like this
public class BankQueryResponse
{
[XmlElement("TRANSACTION_ID")]
public string TransactionId { get; set; }
[XmlElement("MERCHANT_ACC_NO")]
public string MerchantAccNo { get; set; }
[XmlElement("TXN_SIGNATURE")]
public string TxnSignature { get; set; }
[XmlElement("TRAN_DATE")]
public DateTime TranDate { get; set; }
[XmlElement("TXN_STATUS")]
public string TxnStatus { get; set; }
[XmlElement("REFUND_DATE")]
public DateTime RefundDate { get; set; }
[XmlElement("RESPONSE_CODE")]
public string ResponseCode { get; set; }
[XmlElement("RESPONSE_DESC")]
public string ResponseDesc { get; set; }
[XmlAttribute("MERCHANT_TRANID")]
public string MerchantTranId { get; set; }
}
Deseralization Code would be something like this
TransactionResponse result = new TransactionResponse();
if(!string.IsNullOrEmpty(responseData))
{
XmlSerializer serializer = new XmlSerializer(typeof(TransactionResponse));
using(TextReader xmlreader = new StringReader(responseData))
{
result = (TransactionResponse) serializer.Deserialize(xmlreader);
}
}
I'm trying to deserialize a xml string to a c# object. This is the message:
<message from='test1#localhost' to='test2#localhost'><result xmlns='urn:xmpp:mam:tmp' id='A6QV1I4TKO81'><forwarded xmlns='urn:xmpp:forward:0'><delay xmlns='urn:xmpp:delay' from='test1#localhost' stamp='2015-07-21T09:12:09Z'></delay><message type='mchat'><subject/><body/></message></forwarded></result></message>
And this is the class
public class Delay {
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName="from")]
public string From { get; set; }
[XmlAttribute(AttributeName="stamp")]
public string Stamp { get; set; }
}
public class Active {
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
}
public class XmppMessage {
[XmlElement(ElementName="body")]
public string Body { get; set; }
[XmlAttribute(AttributeName="lang")]
public string Lang { get; set; }
[XmlAttribute(AttributeName="type")]
public string Type { get; set; }
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
[XmlAttribute(AttributeName="to")]
public string To { get; set; }
}
public class Forwarded {
[XmlElement(ElementName="delay")]
public Delay Delay { get; set; }
[XmlElement(ElementName="message")]
public XmppMessage Message { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
}
public class Result {
[XmlElement(ElementName="forwarded")]
public Forwarded Forwarded { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
}
[XmlRoot(ElementName="message")]
public class MessageHistory {
[XmlElement(ElementName="result")]
public Result Result { get; set; }
[XmlAttribute(AttributeName="from")]
public string From { get; set; }
[XmlAttribute(AttributeName="to")]
public string To { get; set; }
}
This is the code to deserialise:
MessageHistory messageNode;
XmlSerializer serializer = new XmlSerializer(typeof(MessageHistory));
using (StringReader reader = new StringReader(message))
{
messageNode = (MessageHistory)(serializer.Deserialize(reader));
}
The object property "from" and "to" are fine but the "Result" is returning null. I can't understand what I'm missing here...
The problem is the namespaces in the XML. you have to specify the namespaces explicitly, like this:
public class Forwarded
{
[XmlElement(ElementName = "delay", Namespace = "urn:xmpp:delay")]
public Delay Delay { get; set; }
[XmlElement(ElementName = "message")]
public XmppMessage Message { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
}
public class Result
{
[XmlElement(ElementName = "forwarded", Namespace = "urn:xmpp:forward:0")]
public Forwarded Forwarded { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[XmlRoot(ElementName = "message")]
public class MessageHistory
{
[XmlElement(ElementName = "result", Namespace = "urn:xmpp:mam:tmp")]
public Result Result { get; set; }
[XmlAttribute(AttributeName = "from")]
public string From { get; set; }
[XmlAttribute(AttributeName = "to")]
public string To { get; set; }
}