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
}
Related
I am using XSD2Code++ 2019 tool for visual studio to generate POCOs from aset of 5 xsds. I have added the POCO class below. I see that it has the right xml decorators for it to serialize properly. But I really fail to understand or figure out why the 3rd level object in the returned deserialized data is always empty and not typecasted to the correct type.
I have tried changing attributes to xmlArray and xmlArrayElement too but none of that worked.
POCO class-
https://gist.github.com/nimisha84/b86a4bb2bf37aea6ec351a9f6e331bed
Sample xml response which has null values after deserialization using c# code-
<?xml version="1.0" encoding="UTF-8"?>
<IntuitResponse xmlns="http://schema.intuit.com/finance/v3" time="2019-07-05T14:29:08.603-07:00">
<QueryResponse startPosition="1" maxResults="1" totalCount="1">
<Invoice domain="QBO" sparse="false">
<Id>8633</Id>
<SyncToken>14</SyncToken>
<MetaData>
<CreateTime>2019-01-09T11:32:12-08:00</CreateTime>
<LastUpdatedTime>2019-06-05T12:49:40-07:00</LastUpdatedTime>
</MetaData>
<CustomField>
<DefinitionId>1</DefinitionId>
<Name>CustomPO</Name>
<Type>StringType</Type>
<StringValue>Gold</StringValue>
</CustomField>
<DocNumber>2830</DocNumber>
<TxnDate>2019-01-09</TxnDate>
<CurrencyRef name="United States Dollar">USD</CurrencyRef>
<ExchangeRate>1</ExchangeRate>
<PrivateNote>Voided - Voided</PrivateNote>
<Line>
<Id>1</Id>
<LineNum>1</LineNum>
<Description>Description</Description>
<Amount>0</Amount>
<DetailType>SalesItemLineDetail</DetailType>
<SalesItemLineDetail>
<ItemRef name="Name27140">815</ItemRef>
<Qty>0</Qty>
<TaxCodeRef>NON</TaxCodeRef>
</SalesItemLineDetail>
</Line>
<Line>
<Amount>0</Amount>
<DetailType>SubTotalLineDetail</DetailType>
<SubTotalLineDetail />
</Line>
<TxnTaxDetail>
<TotalTax>0</TotalTax>
</TxnTaxDetail>
<CustomerRef name="a4">2561</CustomerRef>
<DueDate>2019-01-09</DueDate>
<TotalAmt>0</TotalAmt>
<HomeTotalAmt>0</HomeTotalAmt>
<ApplyTaxAfterDiscount>false</ApplyTaxAfterDiscount>
<PrintStatus>NeedToPrint</PrintStatus>
<EmailStatus>NotSet</EmailStatus>
<Balance>0</Balance>
<Deposit>0</Deposit>
<AllowIPNPayment>false</AllowIPNPayment>
<AllowOnlinePayment>false</AllowOnlinePayment>
<AllowOnlineCreditCardPayment>false</AllowOnlineCreditCardPayment>
<AllowOnlineACHPayment>false</AllowOnlineACHPayment>
</Invoice>
</QueryResponse>
</IntuitResponse>
Code to deserialize-
string responseText = apiResponse.ReadToEnd();
var responseSerializer = new XmlObjectSerializer();
IntuitResponse restResponse =
(IntuitResponse)this.responseSerializer.Deserialize<IntuitResponse>(responseText);
res=restResponse.Items[0] as QueryResponse;
here QueryResponse is not having Invoice(of type IntuitEntity) object returned. Instead empty value is returned. See screenshot.
https://imgur.com/a/5yF6Khb
I really need help to figure out why the 3rd level property is returned as empty.
I tested code below and it works. I manually generated the classes which produces simpler results than using tools.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string responseText = File.ReadAllText(FILENAME);
StringReader reader = new StringReader(responseText);
XmlReader xReader = XmlReader.Create(reader);
XmlSerializer serializer = new XmlSerializer(typeof(IntuitResponse));
IntuitResponse response = (IntuitResponse)serializer.Deserialize(xReader);
}
}
[XmlRoot(ElementName = "IntuitResponse", Namespace = "http://schema.intuit.com/finance/v3")]
public class IntuitResponse
{
[XmlAttribute("time")]
public DateTime time { get; set; }
[XmlElement(ElementName = "QueryResponse", Namespace = "http://schema.intuit.com/finance/v3")]
public QueryResponse response { get; set; }
}
public class QueryResponse
{
[XmlAttribute("startPosition")]
public int startPosition { get; set; }
[XmlAttribute("maxResults")]
public int maxResults { get; set; }
[XmlAttribute("totalCount")]
public int totalCount { get; set; }
[XmlElement(ElementName = "Invoice", Namespace = "http://schema.intuit.com/finance/v3")]
public Invoice invoice { get; set; }
}
public class Invoice
{
[XmlAttribute("domain")]
public string domain { get; set; }
[XmlAttribute("sparse")]
public Boolean sparse { get; set; }
public int Id { get; set; }
public int SyncToken { get; set; }
[XmlElement(ElementName = "MetaData", Namespace = "http://schema.intuit.com/finance/v3")]
public MetaData metaData { get; set; }
[XmlElement(ElementName = "CustomField", Namespace = "http://schema.intuit.com/finance/v3")]
public CustomField customField { get; set; }
public int DocNumber { get; set; }
public DateTime TxnDate { get; set; }
[XmlElement(ElementName = "CurrencyRef", Namespace = "http://schema.intuit.com/finance/v3")]
public CurrencyRef currencyRef { get; set; }
public int ExchangeRate { get; set; }
public string PrivateNote { get; set; }
[XmlElement(ElementName = "Line", Namespace = "http://schema.intuit.com/finance/v3")]
public List<Line> line { get; set; }
[XmlElement(ElementName = "TxnTaxDetail", Namespace = "http://schema.intuit.com/finance/v3")]
public TxnTaxDetail txnTaxDetail { get; set; }
[XmlElement(ElementName = "CustomerRef", Namespace = "http://schema.intuit.com/finance/v3")]
public CustomerRef CustomerRef { get; set; }
public DateTime DueDate { get; set; }
public int TotalAmt { get; set; }
public int HomeTotalAmt { get; set; }
public Boolean ApplyTaxAfterDiscount { get; set; }
public string PrintStatus { get; set; }
public string EmailStatus { get; set; }
public int Balance { get; set; }
public int Deposit { get; set; }
public Boolean AllowIPNPayment { get; set; }
public Boolean AllowOnlinePayment { get; set; }
public Boolean AllowOnlineCreditCardPayment { get; set; }
public Boolean AllowOnlineACHPayment { get; set; }
}
public class MetaData
{
public DateTime CreateTime { get; set; }
public DateTime LastUpdatedTime { get; set; }
}
public class CustomField
{
public int DefinitionId { get; set; }
public string Name { get; set; }
public string Type { get; set; }
public string StringValue { get; set; }
}
public class CurrencyRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class Line
{
public int Id { get; set; }
public int LineNum { get; set; }
public string Description { get; set; }
public decimal Amount { get; set; }
public string DetailType { get; set; }
[XmlElement(ElementName = "SalesItemLineDetail", Namespace = "http://schema.intuit.com/finance/v3")]
public SalesItemLineDetail salesItemLineDetail { get; set; }
}
public class CustomerRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class SalesItemLineDetail
{
[XmlElement(ElementName = "ItemRef", Namespace = "http://schema.intuit.com/finance/v3")]
public ItemRef itemRef { get; set; }
public int Qty { get; set; }
public string TaxCodeRef { get; set; }
}
public class ItemRef
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlText]
public string value { get; set; }
}
public class TxnTaxDetail
{
public int TotalTax { get; set; }
}
}
I have the following xml file which I have tried to load using method to turn it into a business object however it says expecting > at line 1 ,40 but when I look at it looks fine.
XmlSerializer serializer = new XmlSerializer(typeof( SalesOrderXml));
using (TextReader reader = new StringReader(testData))
{
SalesOrderXmlresult = (SalesOrderXml) serializer.Deserialize(reader);
}
Xml here cause of the length of it it would have exceeded the article.
https://pastebin.com/pepp1QDe
I do not no what i am doing wrong as I used the online xml to poco generator to help me out as a its a long file.
Any tips of what i might be doing wrong I checked for hidden chars in the file and there is none.
public class SalesOrderXml
{
[XmlRoot(ElementName = "ORDER_ITEM")]
public class ORDER_ITEM
{
[XmlElement(ElementName = "PRODUCT_ID")]
public string PRODUCT_ID { get; set; }
[XmlElement(ElementName = "STOCK_CODE")]
public string STOCK_CODE { get; set; }
[XmlElement(ElementName = "ITEM_TYPE")]
public string ITEM_TYPE { get; set; }
[XmlElement(ElementName = "DESCRIPTION")]
public string DESCRIPTION { get; set; }
[XmlElement(ElementName = "QUANTITY")]
public string QUANTITY { get; set; }
[XmlElement(ElementName = "PRICE")]
public string PRICE { get; set; }
[XmlElement(ElementName = "HEIGHT")]
public string HEIGHT { get; set; }
[XmlElement(ElementName = "WIDTH")]
public string WIDTH { get; set; }
[XmlElement(ElementName = "HINGE_HOLES")]
public string HINGE_HOLES { get; set; }
[XmlElement(ElementName = "DRILL_TOP")]
public string DRILL_TOP { get; set; }
[XmlElement(ElementName = "DRILL_BOTTOM")]
public string DRILL_BOTTOM { get; set; }
[XmlElement(ElementName = "DRILL_TOP_1")]
public string DRILL_TOP_1 { get; set; }
[XmlElement(ElementName = "DRILL_TOP_2")]
public string DRILL_TOP_2 { get; set; }
[XmlElement(ElementName = "DRILL_TOP_3")]
public string DRILL_TOP_3 { get; set; }
[XmlElement(ElementName = "RAW")]
public string RAW { get; set; }
[XmlElement(ElementName = "RAH")]
public string RAH { get; set; }
[XmlElement(ElementName = "LAW")]
public string LAW { get; set; }
[XmlElement(ElementName = "LAH")]
public string LAH { get; set; }
[XmlElement(ElementName = "FRAME_TYPE")]
public string FRAME_TYPE { get; set; }
[XmlElement(ElementName = "GLAZING_TYPE")]
public string GLAZING_TYPE { get; set; }
[XmlElement(ElementName = "LENGTH")]
public string LENGTH { get; set; }
[XmlElement(ElementName = "DEPTH")]
public string DEPTH { get; set; }
[XmlElement(ElementName = "CORNER_POSITION")]
public string CORNER_POSITION { get; set; }
[XmlElement(ElementName = "HORIZONTAL_GRAIN")]
public string HORIZONTAL_GRAIN { get; set; }
[XmlElement(ElementName = "PANEL_TYPE")]
public string PANEL_TYPE { get; set; }
[XmlElement(ElementName = "PANEL_EDGE")]
public string PANEL_EDGE { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE")]
public string PROFILED_EDGE { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_FRONT")]
public string PROFILED_EDGE_FRONT { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_BACK")]
public string PROFILED_EDGE_BACK { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_LEFT")]
public string PROFILED_EDGE_LEFT { get; set; }
[XmlElement(ElementName = "PROFILED_EDGE_RIGHT")]
public string PROFILED_EDGE_RIGHT { get; set; }
[XmlElement(ElementName = "EDGE_TYPE")]
public string EDGE_TYPE { get; set; }
[XmlElement(ElementName = "ANGLES_REQUIRED")]
public string ANGLES_REQUIRED { get; set; }
[XmlElement(ElementName = "ANGLE_LENGTH")]
public string ANGLE_LENGTH { get; set; }
[XmlElement(ElementName = "ANGLE_DEPTH")]
public string ANGLE_DEPTH { get; set; }
[XmlElement(ElementName = "THICKNESS")]
public string THICKNESS { get; set; }
[XmlElement(ElementName = "REVERSE_COLOUR")]
public string REVERSE_COLOUR { get; set; }
}
[XmlRoot(ElementName = "DELIVERY_ADDRESS")]
public class DELIVERY_ADDRESS
{
[XmlElement(ElementName = "ADDRESS1")]
public string ADDRESS1 { get; set; }
[XmlElement(ElementName = "ADDRESS2")]
public string ADDRESS2 { get; set; }
[XmlElement(ElementName = "TOWN")]
public string TOWN { get; set; }
[XmlElement(ElementName = "POSTCODE")]
public string POSTCODE { get; set; }
[XmlElement(ElementName = "COUNTY")]
public string COUNTY { get; set; }
[XmlElement(ElementName = "COUNTRY")]
public string COUNTRY { get; set; }
}
[XmlRoot(ElementName = "ORDER")]
public class ORDER
{
[XmlElement(ElementName = "ORDER_ID")]
public string ORDER_ID { get; set; }
[XmlElement(ElementName = "ORDERED_BY")]
public string ORDERED_BY { get; set; }
[XmlElement(ElementName = "ORDER_REFERENCE")]
public string ORDER_REFERENCE { get; set; }
[XmlElement(ElementName = "CUSTOMER_ID")]
public string CUSTOMER_ID { get; set; }
[XmlElement(ElementName = "ACCOUNT_REFERENCE")]
public string ACCOUNT_REFERENCE { get; set; }
[XmlElement(ElementName = "ORDER_TYPE")]
public string ORDER_TYPE { get; set; }
[XmlElement(ElementName = "ORDER_RANGE")]
public string ORDER_RANGE { get; set; }
[XmlElement(ElementName = "ORDER_COLOUR")]
public string ORDER_COLOUR { get; set; }
[XmlElement(ElementName = "EDGE_TYPE")]
public string EDGE_TYPE { get; set; }
[XmlElement(ElementName = "REVERSE_COLOUR")]
public string REVERSE_COLOUR { get; set; }
[XmlElement(ElementName = "HORIZONTAL_GRAIN")]
public string HORIZONTAL_GRAIN { get; set; }
[XmlElement(ElementName = "HANDLE_TYPE")]
public string HANDLE_TYPE { get; set; }
[XmlElement(ElementName = "NOTES")]
public string NOTES { get; set; }
[XmlElement(ElementName = "ORDER_DATE")]
public string ORDER_DATE { get; set; }
[XmlElement(ElementName = "DELIVERY_DATE")]
public string DELIVERY_DATE { get; set; }
[XmlElement(ElementName = "ADDITIONAL_DELIVERY_INFO")]
public string ADDITIONAL_DELIVERY_INFO { get; set; }
[XmlElement(ElementName = "ORDER_ITEM")]
public List<ORDER_ITEM> ORDER_ITEM { get; set; }
[XmlElement(ElementName = "DELIVERY_ADDRESS")]
public DELIVERY_ADDRESS DELIVERY_ADDRESS { get; set; }
[XmlElement(ElementName = "DELIVERY_TYPE")]
public string DELIVERY_TYPE { get; set; }
[XmlElement(ElementName = "DELIVERY_PRICE")]
public string DELIVERY_PRICE { get; set; }
[XmlElement(ElementName = "DELIVERY_CODE")]
public string DELIVERY_CODE { get; set; }
[XmlElement(ElementName = "TOTAL_EX_VAT")]
public string TOTAL_EX_VAT { get; set; }
[XmlElement(ElementName = "TOTAL_INC_VAT")]
public string TOTAL_INC_VAT { get; set; }
[XmlElement(ElementName = "TOTAL_INC_DELIVERY")]
public string TOTAL_INC_DELIVERY { get; set; }
}
}
Although I didn't get the same error as you when I setup a test case using your code, I did get an error about "ORDER" being unexpected.
I then successfully deserialized the XML by specifying SalesOrderXml.ORDER as the root class, rather than SalesOrderXml.
XmlSerializer serializer = new XmlSerializer(typeof(SalesOrderXml.ORDER));
using (TextReader reader = new StringReader(testData))
{
var ob = (SalesOrderXml.ORDER)serializer.Deserialize(reader);
}
I set testData exactly the same as your pastebin string (with the spaces trimmed as per Renzo's comment), and my test case ran successfully.
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; }
}
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);
So I have xml from a url that looks like this:
<restaurantFoodImpls>
<RestaurantFood Price="1689.7594" ID="426" Description="quis egreddior glavans brevens, si eggredior. vobis e fecundio, fecundio, et quoque nomen gravum parte volcans">
<foodItem Name="Frances93" ID="548"/>
<restaurant Name="Alana59" PhoneNumber="7954016342" MobileNumber="372206-3626" LastName="Hickman" ID="1" FirstName="Gabrielle"/>
</RestaurantFood>
<RestaurantFood Price="14.225095" ID="520" Description="in plorum egreddior plorum e pladior in linguens essit. novum habitatio Versus plurissimum volcans linguens estum.">
<foodItem Name="Frances93" ID="548"/>
<restaurant Name="Alana59" PhoneNumber="7954016342" MobileNumber="372206-3626" LastName="Hickman" ID="1" FirstName="Gabrielle"/>
</RestaurantFood>
</restaurantFoodImpls>
How to parse it into objects using C#?
I have tried using the deserializer but my problem is that I want the properties of the elements read from the attributes in XML, and I couldn't get them.
var stream = File.Open(filename, FileMode.Open);
XmlSerializer ser = new XmlSerializer(typeof(RestaurantFoodImpls));
var result = ser.Deserialize(stream) as RestaurantFoodImpls;
public class FoodItem
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string ID { get; set; }
}
public class Restaurant
{
[XmlAttribute]
public string Name { get; set; }
[XmlAttribute]
public string PhoneNumber { get; set; }
[XmlAttribute]
public string MobileNumber { get; set; }
[XmlAttribute]
public string LastName { get; set; }
[XmlAttribute]
public string ID { get; set; }
[XmlAttribute]
public string FirstName { get; set; }
}
public class RestaurantFood
{
[XmlAttribute]
public string Price { get; set; }
[XmlAttribute]
public string ID { get; set; }
[XmlAttribute]
public string Description { get; set; }
[XmlElement("foodItem")]
public FoodItem foodItem { get; set; }
[XmlElement("restaurant")]
public Restaurant restaurant { get; set; }
}
[XmlRoot("restaurantFoodImpls")]
public class RestaurantFoodImpls
{
[XmlElement("RestaurantFood")]
public List<RestaurantFood> RestaurantFood { get; set; }
}