Deserialization not filling data - C# - c#

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

Related

Error deserializing XML file into C# class of objects

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

c# complex and large xml loading

I have some problems parsing huge xml in c#, mostly because I returned from apex to c# after a long time. So far I cant get working even this
private void read_Click(object sender, EventArgs e)
{
XElement xmlDoc = XElement.Load(#"D:\\AOI\\Samples\\Error\\60A84130868D_20180428035150_AOI-mek1.xml");
var loaded_File =
from fileInfo in xmlDoc.Descendants("result_file")
select new File
{
filename = fileInfo.Element("designator").Value,
supplier = fileInfo.Element("supplier").Value,
date_created = fileInfo.Element("date").Value,
station_ID = fileInfo.Element("station_ID").Value,
operator_ID = fileInfo.Element("operator_ID").Value,
program = fileInfo.Element("program").Value,
side_variant = fileInfo.Element("side_variant").Value
};
foreach(var item in loaded_File) {
System.Diagnostics.Debug.WriteLine(item.ToString());
}
}
Xml file looks as follows with multiple good_no and error_no, can someone navigate me how to load the file properly? I need it afterwards to insert it into database, but that should be just fine.
<result_file>
<filename>60Axxxxxek1</filename>
<supplier>Maxxxxz</supplier>
<date>20xxxx5150</date>
<station_ID>Axxxx1</station_ID>
<operator_ID></operator_ID>
<program>Xxxx01</program>
<side_variant>A</side_variant>
<pcbs_in_panel>0</pcbs_in_panel>
<serial>60xxxxxx8D</serial>
<status>GOOD</status>
<starttime>20180xxxxxx150</starttime>
<lot_no></lot_no>
<info>
<window_no>354</window_no>
<packs_no>343</packs_no>
<error_total>1</error_total>
<error_conf>0</error_conf>
<inspection_time>5</inspection_time>
<panel_image>AOxxxxx_A.jpg</panel_image>
<panel_image_location>x:\xml</panel_image_location>
<ng_image_location>x:\xml\Xxxxx0428</ng_image_location>
<repaired>0</repaired>
</info>
<errors>
<error_no name="1">
<designator></designator>
<pin></pin>
<stamp_name>Bridge:Short</stamp_name>
<package_name></package_name>
<errortype>-</errortype>
<error_contents></error_contents>
<pcb_no></pcb_no>
<feeder_no></feeder_no>
<pos_x>8760</pos_x>
<pos_y>4600</pos_y>
<window>-313</window>
<ng_message></ng_message>
<comment>(* *){Bridge:Short}</comment>
<ng_image>Xxxxxx13.jpg</ng_image>
</error_no>
</errors>
<goods>
<good_no name="1">
<designator>Ixxx1</designator>
<pin>Ixxx1</pin>
<stamp_name>Ixxxxrat</stamp_name>
<package_name>Ixxxx1</package_name>
<pcb_no></pcb_no>
<feeder_no></feeder_no>
<pos_x>3082</pos_x>
<pos_y>3202</pos_y>
<window>+1</window>
<comment>(* *){Ixxxxat}</comment>
</good_no>
</goods>
</result_file>
Thanks for advices.
EDIT:
I have also prepared classes for that
public class File
{
public string name { get; set; }
public string filename { get; set; }
public string supplier { get; set; }
public string date_created { get; set; }
public string station_ID { get; set; }
public string operator_ID { get; set; }
public string program { get; set; }
public string side_variant { get; set; }
public string pcbs_in_panel { get; set; }
public string serial { get; set; }
public string status { get; set; }
public string starttime { get; set; }
public string lot_no { get; set; }
public string window_no { get; set; }
public string packs_no { get; set; }
public string error_total { get; set; }
public string error_conf { get; set; }
public string inspection_time { get; set; }
public string panel_image { get; set; }
public string panel_image_location { get; set; }
public string ng_image_location { get; set; }
public string repaired { get; set; }
public List<Good> Goods = new List<Good>();
public List<Error> Errors = new List<Error>();
}
public class Good
{
public List<Good_no> Good_ones = new List<Good_no>();
}
public class Error
{
public List<Error_no> Error_ones = new List<Error_no>();
}
public class Good_no
{
public string name { get; set; }
public string designator { get; set; }
public string pin { get; set; }
public string stamp_name { get; set; }
public string package_name { get; set; }
public string pcb_no { get; set; }
public string feeder_no { get; set; }
public string pos_x { get; set; }
public string pos_y { get; set; }
public string window { get; set; }
public string comment { get; set; }
}
public class Error_no
{
public string name { get; set; }
public string designator { get; set; }
public string pin { get; set; }
public string stamp_name { get; set; }
public string package_name { get; set; }
public string errortype { get; set; }
public string error_contents { get; set; }
public string pcb_no { get; set; }
public string feeder_no { get; set; }
public string pos_x { get; set; }
public string pos_y { get; set; }
public string window { get; set; }
public string ng_message { get; set; }
public string comment { get; set; }
public string ng_image { get; set; }
}
You should simplify the class structure:
public class File
{
public string Filename { get; set; }
public string Supplier { get; set; }
// ...
public List<Good> Goods { get; set; }
public List<Error> Errors { get; set; }
}
public class Good
{
public string Name { get; set; }
public string Designator { get; set; }
public string Pin { get; set; }
// ...
}
public class Error
{
public string Name { get; set; }
public string Designator { get; set; }
// ...
}
Then the reading would look like this:
var xmlDoc = XElement.Load("test.xml");
var loadedFile = new File
{
Filename = xmlDoc.Element("filename").Value,
Supplier = xmlDoc.Element("supplier").Value,
// ...
Goods = (from good in xmlDoc.Element("goods").Elements("good_no")
select new Good
{
Name = good.Attribute("name").Value,
Designator = good.Element("designator").Value,
Pin = good.Element("pin").Value
// ...
})
.ToList()
};
If you want to read the XML-File, I recommmend you to deserialize the XML-files.
For this, your class-definition isn't complete. In Visual Studio is a tool, called xsd.exe. With this tool you can transform your XML-File first in a XSD-Schema. From the XSD-Schema you can generate the required classes.
To transform to XSD-Schema: xsd.exe {Filename.xml}
To transform to C#-Classes: xsd.exe /c {Filename.xsd}
XSD have many more options (see: https://msdn.microsoft.com/de-de/library/x6c1kb0s(v=vs.120).aspx)
If you have the correct classes you can read the XML-File with the XMLSerializer (see: https://msdn.microsoft.com/de-de/library/tz8csy73(v=vs.110).aspx)

Deserialize xml xmpp message to object

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

Can not deserialize Xml getting from api

I am using World Weather Online API to get the weathers of specific location. My problem is while I am trying to deserialize XML output coming from API Response stream, I am getting error with: There is a problem with XML document (1,1).
Uri apiURL = new Uri(#"http://api.worldweatheronline.com/free/v1/weather.ashx?q=Dhaka&format=xml&num_of_days=1&date=today&key=jzb88bpzb5yvaegukmq97mee");
Stream result = RequestHandler.Process(apiURL.ToString());
XmlSerializer des = new XmlSerializer(typeof(LocalWeather));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
LocalWeather data = (LocalWeather)obj;
Sample XML file from Web API:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<request>
<type>City</type>
<query>Dhaka, Bangladesh</query>
</request>
<current_condition>
<observation_time>01:57 PM</observation_time>
<temp_C>33</temp_C>
<temp_F>91</temp_F>
<weatherCode>113</weatherCode>
<weatherIconUrl>
<![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[Clear ]]>
</weatherDesc>
<windspeedMiles>2</windspeedMiles>
<windspeedKmph>4</windspeedKmph>
<winddirDegree>77</winddirDegree>
<winddir16Point>ENE</winddir16Point>
<precipMM>0.0</precipMM>
<humidity>76</humidity>
<visibility>10</visibility>
<pressure>1006</pressure>
<cloudcover>2</cloudcover>
</current_condition>
<weather>
<date>2013-10-11</date>
<tempMaxC>36</tempMaxC>
<tempMaxF>97</tempMaxF>
<tempMinC>25</tempMinC>
<tempMinF>77</tempMinF>
<windspeedMiles>5</windspeedMiles>
<windspeedKmph>8</windspeedKmph>
<winddirection>ENE</winddirection>
<winddir16Point>ENE</winddir16Point>
<winddirDegree>65</winddirDegree>
<weatherCode>113</weatherCode>
<weatherIconUrl>
<![CDATA[http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0001_sunny.png]]>
</weatherIconUrl>
<weatherDesc>
<![CDATA[Sunny]]>
</weatherDesc>
<precipMM>0.0</precipMM>
</weather>
</data>
LocalWeather class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace APISample
{
public class LocalWeather
{
public Data data { get; set; }
}
public class Data
{
public List<Current_Condition> current_Condition { get; set; }
public List<Request> request { get; set; }
public List<Weather> weather { get; set; }
}
public class Current_Condition
{
public DateTime observation_time { get; set; }
public DateTime localObsDateTime { get; set; }
public int temp_C { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc> weatherDesc { get; set; }
public List<WeatherIconUrl> weatherIconUrl { get; set; }
public float precipMM { get; set; }
public float humidity { get; set; }
public int visibility { get; set; }
public int pressure { get; set; }
public int cloudcover { get; set; }
}
public class Request
{
public string query { get; set; }
public string type { get; set; }
}
public class Weather
{
public DateTime date { get; set; }
public int tempMaxC { get; set; }
public int tempMaxF { get; set; }
public int tempMinC { get; set; }
public int tempMinF { get; set; }
public int windspeedMiles { get; set; }
public int windspeedKmph { get; set; }
public int winddirDegree { get; set; }
public string winddir16Point { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc> weatherDesc { get; set; }
public List<WeatherIconUrl> weatherIconUrl { get; set; }
public float precipMM { get; set; }
}
public class WeatherDesc
{
public string value { get; set; }
}
public class WeatherIconUrl
{
public string value { get; set; }
}
}
You need to update the class to match the schema of the XML structure (these are case sensitive).
You can start with your existing file using the attributes found in System.Xml.Serialization.
[XmlRoot("data")]
public class Data {
// and so on..
}
Or you could use the XSD tool to generate the class for you following these steps.
Create schema for the XML returns from the service (Xml -> Create Schema)
In VS Studio tools run this command: XSD XmlSchema.xsd /c (where XmlSchema.xsd is the schema produced in step 1).
The way that your model is set up right now, you have LocalWeather as the root, whereas in the actual XML the root is Data. That's why you're getting the "Invalid root node" error. So, instead of
XmlSerializer des = new XmlSerializer(typeof(LocalWeather));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
LocalWeather data = (LocalWeather)obj;
try
XmlSerializer des = new XmlSerializer(typeof(Data));
StreamReader tr = new StreamReader(result);
Object obj = des.Deserialize(tr);
Data data = (Data)obj;

Can't Deserialize XML

I am trying to deserialize the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<jobInfo
xmlns="http://www.force.com/2009/06/asyncapi/dataload">
<id>750x0000000005LAAQ</id>
<operation>insert</operation>
<object>Contact</object>
<createdById>005x0000000wPWdAAM</createdById>
<createdDate>2009-09-01T16:42:46.000Z</createdDate>
<systemModstamp>2009-09-01T16:42:46.000Z</systemModstamp>
<state>Open</state>
<concurrencyMode>Parallel</concurrencyMode>
<contentType>CSV</contentType>
<numberBatchesQueued>0</numberBatchesQueued>
<numberBatchesInProgress>0</numberBatchesInProgress>
<numberBatchesCompleted>0</numberBatchesCompleted>
<numberBatchesFailed>0</numberBatchesFailed>
<numberBatchesTotal>0</numberBatchesTotal>
<numberRecordsProcessed>0</numberRecordsProcessed>
<numberRetries>0</numberRetries>
<apiVersion>28.0</apiVersion>
</jobInfo>
I have created this object:
public class JobInfo
{
public string xmlns { get; set; }
public string id { get; set; }
public string operation { get; set; }
public string #object { get; set; }
public string createdById { get; set; }
public string createdDate { get; set; }
public string systemModstamp { get; set; }
public string state { get; set; }
public string concurrencyMode { get; set; }
public string contentType { get; set; }
public string numberBatchesQueued { get; set; }
public string numberBatchesInProgress { get; set; }
public string numberBatchesCompleted { get; set; }
public string numberBatchesFailed { get; set; }
public string numberBatchesTotal { get; set; }
public string numberRecordsProcessed { get; set; }
public string numberRetries { get; set; }
public string apiVersion { get; set; }
}
public class RootObject
{
public JobInfo jobInfo { get; set; }
}
And, I am using this code:
XmlSerializer serializer = new XmlSerializer(typeof(RootObject));
StringReader rdr = new StringReader(response);
RootObject resultingMessage = (RootObject)serializer.Deserialize(rdr);
However, I get this error:
There is an error in XML document (1, 40).
{"<jobInfo xmlns='http://www.force.com/2009/06/asyncapi/dataload'> was not expected."}
How can I account for the xmlns attribute? My code has it as a property (thus, it fails)...
Currently your code is expecting the xmlns as element, not the attribute.
You should add the XmlSerialization attributes to your class, like this:
[XmlRoot("jobInfo", Namespace="http://www.force.com/2009/06/asyncapi/dataload"]
public class JobInfo
{
[XmlAttribute]
public string xmlns { get; set; }
[XmlElement(ElementName = "id")]
public string id { get; set; }
....
}
You can find more information in MSDN articles:
Controlling XML Serialization Using Attributes
Examples of XML Serialization
Try using the XmlRootAttribute to specify the Namespace.
[XmlRoot("jobInfo", Namespace = "http://www.force.com/2009/06/asyncapi/dataload")]
public class JobInfo
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("operation")]
public string Operation { get; set; }
[XmlElement("object")]
public string Object { get; set; }
[XmlElement("createdById")]
public string CreatedById { get; set; }
[XmlElement("createdDate")]
public DateTime CreatedDate { get; set; }
[XmlElement("systemModstamp")]
public DateTime SystemModstamp { get; set; }
[XmlElement("state")]
public string State { get; set; }
[XmlElement("concurrencyMode")]
public string ConcurrencyMode { get; set; }
[XmlElement("contentType")]
public string ContentType { get; set; }
[XmlElement("numberBatchesQueued")]
public string NumberBatchesQueued { get; set; }
[XmlElement("numberBatchesInProgress")]
public string NumberBatchesInProgress { get; set; }
[XmlElement("numberBatchesCompleted")]
public string NumberBatchesCompleted { get; set; }
[XmlElement("numberBatchesFailed")]
public string NumberBatchesFailed { get; set; }
[XmlElement("numberBatchesTotal")]
public string NumberBatchesTotal { get; set; }
[XmlElement("numberRecordsProcessed")]
public string numberRecordsProcessed { get; set; }
[XmlElement("numberRetries")]
public string NumberRetries { get; set; }
[XmlElement("apiVersion")]
public string ApiVersion { get; set; }
}
Code:
var xml = #"<?xml version=""1.0"" encoding=""UTF-8""?>
<jobInfo xmlns=""http://www.force.com/2009/06/asyncapi/dataload"">
<id>750x0000000005LAAQ</id>
<operation>insert</operation>
<object>Contact</object>
<createdById>005x0000000wPWdAAM</createdById>
<createdDate>2009-09-01T16:42:46.000Z</createdDate>
<systemModstamp>2009-09-01T16:42:46.000Z</systemModstamp>
<state>Open</state>
<concurrencyMode>Parallel</concurrencyMode>
<contentType>CSV</contentType>
<numberBatchesQueued>0</numberBatchesQueued>
<numberBatchesInProgress>0</numberBatchesInProgress>
<numberBatchesCompleted>0</numberBatchesCompleted>
<numberBatchesFailed>0</numberBatchesFailed>
<numberBatchesTotal>0</numberBatchesTotal>
<numberRecordsProcessed>0</numberRecordsProcessed>
<numberRetries>0</numberRetries>
<apiVersion>28.0</apiVersion>
</jobInfo>";
var serializer = new XmlSerializer(typeof(JobInfo));
JobInfo jobInfo;
using(var stream = new StringReader(xml))
using(var reader = XmlReader.Create(stream))
{
jobInfo = (JobInfo)serializer.Deserialize(reader);
}
Add the namespace
[XmlRoot("jobInfo",Namespace = "http://www.force.com/2009/06/asyncapi/dataload")]
public class JobInfo
{
// get rid of the xmlns property
// other properties stay
}
// there is no rootobject, JobInfo is your root
XmlSerializer serializer = new XmlSerializer(typeof(JobInfo));
StringReader rdr = new StringReader(response);
JobInfo resultingMessage = (JobInfo)serializer.Deserialize(rdr);

Categories