I'm trying to deserialize a complex XML file. i have my main class structured so it gets all of the info in the first child nodes, I even have it so that i can obtain the ClientName which is two layers deep. However, anything beyond that does not seem to work. I get a List item with a count of 1 but no information is inside the list.
My OrderTaxes and OrderTransactions lists come back with a Count = 1 but all of the fields are null.
I'm positive it is a problem with my class structure and any help towards correcting this would be very appreciated.
Here is the XML:
<OrderDetail>
<MessageTypeCode>82540</MessageTypeCode>
<OrderDetailId>59339463</OrderDetailId>
<ClientInfo>
<ClientName>LenderName will appear here</ClientName>
</ClientInfo>
<OrderTaxes>
<OrderTax>
<TaxId>9202225</TaxId>
</OrderTax>
</OrderTaxes>
<OrderTransactions>
<OrderTransaction>
<LoanAmount/>
<Title>
<TitleVendors>
<TitleVendor>
<VendorInstructions>blah blah blah blah .</VendorInstructions>
<VendorServices>
<TitleVendorService>
<TitleVendorServiceId>6615159</TitleVendorServiceId>
<ServiceCode>1OWNER</ServiceCode>
<CustomVendorInstructions>blah blah blah blah blah </CustomVendorInstructions>
</TitleVendorService>
</VendorServices>
</TitleVendor>
</TitleVendors>
</Title>
</OrderTransaction>
</OrderTransactions>
</OrderDetail>
And here is the class:
namespace TSIxmlParser
{
[XmlRoot("OrderDetail")]
public class OrderData
{
[XmlElement("MessageTypeCode")]
public string MessageTypeCode { get; set; }
[XmlElement("OrderDetailId")]
public string OrderNumber { get; set; }
[XmlElement("ClientInfo")]
public List<ClientInfo> ClientInfos = new List<ClientInfo>();
[XmlArray("OrderTaxes")]
[XmlArrayItem("OrderTax")]
public List<OrderTax> OrderTaxes = new List<OrderTax>();
[XmlArray("OrderTransactions")]
[XmlArrayItem("OrderTransaction")]
public List<OrderTransaction> OrderTransactions = new List<OrderTransaction>();
}
public class ClientInfo
{
[XmlElement("ClientName")]
public string ClientName { get; set; }
}
public class OrderTax
{
[XmlElement("TaxId")]
public string TaxId { get; set; }
}
public class OrderTransaction
{
[XmlElement("LoanAmount")]
public string LoanAmount { get; set; }
[XmlArray("Title")]
[XmlArrayItem("TitleVendors")]
public List<Title> Titles { get; set; }
}
public class Title
{
[XmlArrayItem("TitleVendors")]
public List<TitleVendors> TitleVendors { get; set; }
}
public class TitleVendors
{
[XmlArray("TitleVendor")]
public List<TitleVendor> TitleVendor { get; set; }
}
public class TitleVendor
{
[XmlElement("VendorInstructions")]
public string VendorInstructions { get; set; }
[XmlArray("VendorServices")]
[XmlArrayItem("TitleVendorService")]
public List<TitleVendorService> VendorServices { get; set; }
}
public class TitleVendorService
{
[XmlElement("TitleVendorServiceId")]
public string TitleVendorServiceId { get; set; }
[XmlElement("ServiceCode")]
public string ServiceCode { get; set; }
[XmlElement("CustomVendorInstructions")]
public string CustomVendorInstructions { get; set; }
}
}
The .NET SDK provides a great tool for this. The XML Schedma Definition Tool (csd.exe).
More Info: http://msdn.microsoft.com/en-us/library/x6c1kb0s(v=vs.110).aspx
I ran through an example using your XML to show you have it works.
First I saved your XML to my desktop to a file named 'sample.xml'
I opened up the VS 2012 Command Prompt as Administrator.
In the Command Prompt, I navigated to the directory where the SDK is installed. For me its installed here (might be different with various OS or VS versions):
C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools
I ran the following command to create an XSD for your XML. (Expect sample.xsd to appear on the desktop)
xsd "c:\users\glenn\desktop\sample.xml" /outputdir:"c:\users\glenn\desktop"
I ran the following command to create a CSharp file from the resultant XSD file.
xsd "c:\users\glenn\desktop\sample.xsd" /classes /outputdir:"c:\users\glenn\desktop"
Excluding the comments, this is the CSharp file that is custom generated for your XML schema. There are additional options to set the namespace and typename. Please review the article above for that detail.
using System.Xml.Serialization;
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class OrderDetail {
private string messageTypeCodeField;
private string orderDetailIdField;
private OrderDetailClientInfo[] clientInfoField;
private OrderDetailOrderTaxesOrderTax[][] orderTaxesField;
private OrderDetailOrderTransactionsOrderTransaction[][] orderTransactionsField;
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string MessageTypeCode {
get {
return this.messageTypeCodeField;
}
set {
this.messageTypeCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OrderDetailId {
get {
return this.orderDetailIdField;
}
set {
this.orderDetailIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ClientInfo", Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public OrderDetailClientInfo[] ClientInfo {
get {
return this.clientInfoField;
}
set {
this.clientInfoField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("OrderTax", typeof(OrderDetailOrderTaxesOrderTax), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public OrderDetailOrderTaxesOrderTax[][] OrderTaxes {
get {
return this.orderTaxesField;
}
set {
this.orderTaxesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("OrderTransaction", typeof(OrderDetailOrderTransactionsOrderTransaction), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public OrderDetailOrderTransactionsOrderTransaction[][] OrderTransactions {
get {
return this.orderTransactionsField;
}
set {
this.orderTransactionsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailClientInfo {
private string clientNameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ClientName {
get {
return this.clientNameField;
}
set {
this.clientNameField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailOrderTaxesOrderTax {
private string taxIdField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TaxId {
get {
return this.taxIdField;
}
set {
this.taxIdField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailOrderTransactionsOrderTransaction {
private string loanAmountField;
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor[][][] titleField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string LoanAmount {
get {
return this.loanAmountField;
}
set {
this.loanAmountField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("TitleVendors", typeof(OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor[]), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
[System.Xml.Serialization.XmlArrayItemAttribute("TitleVendor", typeof(OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false, NestingLevel=1)]
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor[][][] Title {
get {
return this.titleField;
}
set {
this.titleField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor {
private string vendorInstructionsField;
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService[][] vendorServicesField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string VendorInstructions {
get {
return this.vendorInstructionsField;
}
set {
this.vendorInstructionsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlArrayAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlArrayItemAttribute("TitleVendorService", typeof(OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService), Form=System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable=false)]
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService[][] VendorServices {
get {
return this.vendorServicesField;
}
set {
this.vendorServicesField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService {
private string titleVendorServiceIdField;
private string serviceCodeField;
private string customVendorInstructionsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TitleVendorServiceId {
get {
return this.titleVendorServiceIdField;
}
set {
this.titleVendorServiceIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string ServiceCode {
get {
return this.serviceCodeField;
}
set {
this.serviceCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CustomVendorInstructions {
get {
return this.customVendorInstructionsField;
}
set {
this.customVendorInstructionsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class NewDataSet {
private OrderDetail[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("OrderDetail")]
public OrderDetail[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
Hope this helps!
Try using XmlArray and XmlArrayItem on the corresponding properties.
[XmlArray("OrderTaxes")]
[XmlArrayItem("OrderTax")]
public List<OrderTax> OrderTaxes = new List<OrderTax>();
and
[XmlArray("OrderTransactions")]
[XmlArrayItem("OrderTransaction")]
public List<OrderTransaction> OrderTransactions = new List<OrderTransaction>();
This way the serializer will know that these are to be treated as collections and will know how to look for a specific item.
Besides these two I would say that wherever you are defining a list of elements you should use this approach. TitleVendors most likely will need something similar.
Well, I am not sure if you wanted this (raw dump of deserialized XML):
{
MessageTypeCode: 82540,
OrderDetailId: 59339463,
ClientInfo:
{
ClientName: LenderName will appear here
},
OrderTaxes:
{
OrderTax:
{
TaxId: 9202225
}
},
OrderTransactions:
{
OrderTransaction:
{
LoanAmount: {},
Title:
{
TitleVendors:
{
TitleVendor:
{
VendorInstructions: blah blah blah blah .,
VendorServices:
{
TitleVendorService:
{
TitleVendorServiceId: 6615159,
ServiceCode: 1OWNER,
CustomVendorInstructions: blah blah blah blah blah
}
}
}
}
}
}
}
}
So basically I just used Edit -> Paste special -> Paste XML as Classes:
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class OrderDetail
{
private uint messageTypeCodeField;
private uint orderDetailIdField;
private OrderDetailClientInfo clientInfoField;
private OrderDetailOrderTaxes orderTaxesField;
private OrderDetailOrderTransactions orderTransactionsField;
/// <remarks/>
public uint MessageTypeCode
{
get
{
return this.messageTypeCodeField;
}
set
{
this.messageTypeCodeField = value;
}
}
/// <remarks/>
public uint OrderDetailId
{
get
{
return this.orderDetailIdField;
}
set
{
this.orderDetailIdField = value;
}
}
/// <remarks/>
public OrderDetailClientInfo ClientInfo
{
get
{
return this.clientInfoField;
}
set
{
this.clientInfoField = value;
}
}
/// <remarks/>
public OrderDetailOrderTaxes OrderTaxes
{
get
{
return this.orderTaxesField;
}
set
{
this.orderTaxesField = value;
}
}
/// <remarks/>
public OrderDetailOrderTransactions OrderTransactions
{
get
{
return this.orderTransactionsField;
}
set
{
this.orderTransactionsField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailClientInfo
{
private string clientNameField;
/// <remarks/>
public string ClientName
{
get
{
return this.clientNameField;
}
set
{
this.clientNameField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTaxes
{
private OrderDetailOrderTaxesOrderTax orderTaxField;
/// <remarks/>
public OrderDetailOrderTaxesOrderTax OrderTax
{
get
{
return this.orderTaxField;
}
set
{
this.orderTaxField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTaxesOrderTax
{
private uint taxIdField;
/// <remarks/>
public uint TaxId
{
get
{
return this.taxIdField;
}
set
{
this.taxIdField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactions
{
private OrderDetailOrderTransactionsOrderTransaction orderTransactionField;
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransaction OrderTransaction
{
get
{
return this.orderTransactionField;
}
set
{
this.orderTransactionField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransaction
{
private object loanAmountField;
private OrderDetailOrderTransactionsOrderTransactionTitle titleField;
/// <remarks/>
public object LoanAmount
{
get
{
return this.loanAmountField;
}
set
{
this.loanAmountField = value;
}
}
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitle Title
{
get
{
return this.titleField;
}
set
{
this.titleField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitle
{
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendors titleVendorsField;
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendors TitleVendors
{
get
{
return this.titleVendorsField;
}
set
{
this.titleVendorsField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendors
{
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor titleVendorField;
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor TitleVendor
{
get
{
return this.titleVendorField;
}
set
{
this.titleVendorField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendor
{
private string vendorInstructionsField;
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServices vendorServicesField;
/// <remarks/>
public string VendorInstructions
{
get
{
return this.vendorInstructionsField;
}
set
{
this.vendorInstructionsField = value;
}
}
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServices VendorServices
{
get
{
return this.vendorServicesField;
}
set
{
this.vendorServicesField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServices
{
private OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService titleVendorServiceField;
/// <remarks/>
public OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService TitleVendorService
{
get
{
return this.titleVendorServiceField;
}
set
{
this.titleVendorServiceField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class OrderDetailOrderTransactionsOrderTransactionTitleTitleVendorsTitleVendorVendorServicesTitleVendorService
{
private uint titleVendorServiceIdField;
private string serviceCodeField;
private string customVendorInstructionsField;
/// <remarks/>
public uint TitleVendorServiceId
{
get
{
return this.titleVendorServiceIdField;
}
set
{
this.titleVendorServiceIdField = value;
}
}
/// <remarks/>
public string ServiceCode
{
get
{
return this.serviceCodeField;
}
set
{
this.serviceCodeField = value;
}
}
/// <remarks/>
public string CustomVendorInstructions
{
get
{
return this.customVendorInstructionsField;
}
set
{
this.customVendorInstructionsField = value;
}
}
}
All code used:
var xmlString = #
"<OrderDetail>
<MessageTypeCode>82540</MessageTypeCode>
<OrderDetailId>59339463</OrderDetailId>
<ClientInfo>
<ClientName>LenderName will appear here</ClientName>
</ClientInfo>
<OrderTaxes>
<OrderTax>
<TaxId>9202225</TaxId>
</OrderTax>
</OrderTaxes>
<OrderTransactions>
<OrderTransaction>
<LoanAmount/>
<Title>
<TitleVendors>
<TitleVendor>
<VendorInstructions>blah blah blah blah .</VendorInstructions>
<VendorServices>
<TitleVendorService>
<TitleVendorServiceId>6615159</TitleVendorServiceId>
<ServiceCode>1OWNER</ServiceCode>
<CustomVendorInstructions>blah blah blah blah blah </CustomVendorInstructions>
</TitleVendorService>
</VendorServices>
</TitleVendor>
</TitleVendors>
</Title>
</OrderTransaction>
</OrderTransactions>
</OrderDetail>";
var xml = new OrderDetail();
System.Xml.Serialization.XmlSerializer serializer = new
System.Xml.Serialization.XmlSerializer(typeof(OrderDetail));
using(XmlReader reader = XmlReader.Create(new StringReader(xmlString))) {
xml = (OrderDetail) serializer.Deserialize(reader);
}
var xmlDump = xml.Dump();
Since this is still open I thought I'd throw in a quick answer, suitable for XmlSerializer. In making the classes, I assumed a pattern resembling this:
<Foo>
<Bars>
<Bar>
Means that class "Foo" contains a list of instances of class "Bar". A pattern like this:
<Foo>
<Bar>
Means that class "Foo" contains a single reference to an instance of class "Bar". Thus you should only have a single "Title" inside your "OrderTransaction", not a list of them:
public class OrderDetail
{
public string MessageTypeCode { get; set; }
public string OrderDetailId { get; set; }
public ClientInfo ClientInfo { get; set; }
public List<OrderTax> OrderTaxes { get; set; }
public List<OrderTransaction> OrderTransactions { get; set; }
}
public class OrderTransaction
{
public string LoanAmount { get; set; }
public Title Title { get; set; }
}
public class Title
{
public List<TitleVendor> TitleVendors { get; set; }
}
public class TitleVendor
{
public string VendorInstructions { get; set; }
public List<TitleVendorService> VendorServices { get; set; }
}
public class TitleVendorService
{
public string TitleVendorServiceId { get; set; }
public string ServiceCode { get; set; }
public string CustomVendorInstructions { get; set; }
}
public class ClientInfo
{
public string ClientName { get; set; }
}
public class OrderTax
{
public string TaxId { get; set; }
}
None of the XML-related decorations are actually required. XmlElement and XmlArray are only needed if you want to override XmlSerializer's default choices, for instance to rename the element or to handle arrays with polymorphic elements. You can put them if you want to for clarity, or to protect against renaming the property down the road, but I didn't for simplicity.
Here's the test setup. I create an instance of "OrderDetail" from your string, then re-serialize it to XML, then save the original and rewritten XML as files and diff them in a command prompt window:
public static class TestOrderDetail
{
public static string TestString =
#"<OrderDetail>
<MessageTypeCode>82540</MessageTypeCode>
<OrderDetailId>59339463</OrderDetailId>
<ClientInfo>
<ClientName>LenderName will appear here</ClientName>
</ClientInfo>
<OrderTaxes>
<OrderTax>
<TaxId>9202225</TaxId>
</OrderTax>
</OrderTaxes>
<OrderTransactions>
<OrderTransaction>
<LoanAmount/>
<Title>
<TitleVendors>
<TitleVendor>
<VendorInstructions>blah blah blah blah .</VendorInstructions>
<VendorServices>
<TitleVendorService>
<TitleVendorServiceId>6615159</TitleVendorServiceId>
<ServiceCode>1OWNER</ServiceCode>
<CustomVendorInstructions>blah blah blah blah blah </CustomVendorInstructions>
</TitleVendorService>
</VendorServices>
</TitleVendor>
</TitleVendors>
</Title>
</OrderTransaction>
</OrderTransactions>
</OrderDetail>";
public static void Test()
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(OrderDetail));
OrderDetail orderDetail = (OrderDetail)serializer.Deserialize(new StringReader(TestString));
string newTestString = TestWrite(serializer, orderDetail);
var guid = DateTime.Now.Ticks;
var path = Path.GetTempPath();
var file1 = path + Path.DirectorySeparatorChar + "OldOrderDetail_" + guid.ToString() + ".xml";
var file2 = path + Path.DirectorySeparatorChar + "NewOrderDetail_" + guid.ToString() + ".xml";
File.WriteAllText(file1, TestString);
File.WriteAllText(file2, newTestString);
}
catch (Exception e)
{
Debug.Assert(false, e.ToString());
}
}
private static string TestWrite(XmlSerializer serializer, OrderDetail orderDetail)
{
using (var textWriter = new StringWriter())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true; // For testing purposes, disable the xml version and encoding declarations.
settings.Indent = true;
settings.IndentChars = " "; // The indentation used in the test string.
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings))
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", ""); // For testing purposes, disable the xmlns:xsi and xmlns:xsd lines, which were not in the test string.
serializer.Serialize(xmlWriter, orderDetail, ns);
}
return textWriter.ToString();
}
}
}
Here's the result of diffing the old and new XML files:
diff OldOrderDetail_635420738451748332.xml NewOrderDetail_635420738451748332.xml
14c14
< <LoanAmount/>
---
> <LoanAmount />
Other than inserting an extra space for formatting in the empty "LoanAmount" element, there's no difference.
Btw XmlSerializer and DataContractSerializer are complete different. According your sample you need to use XmlSeralizer (not DataContractSerializer).
This is what I have so far. This code produces the following structure:
-OrderTransactions (Count = 1)
- Loan Amount = ""
- Titles (Count = 1)
-TitleVendors (Count = 1)
- VendorInstructions = null
- VendorServices (Count = 0)
It seems to be seeing the nodes inside TitleVendors, but it doesn't grab the information.
<OrderTransactions>
<OrderTransaction>
<LoanAmount /> --this may be NULL - this should not cause the message to fail.
<Title>
<TitleVendors>
<TitleVendor>
<VendorInstructions>Endorsements required: EPA, COMP, PUD. **Attention Abstractor: THIS IS A VA LOAN** **Attention Abstractor: If a PRIVATE ROAD EASEMENT exists, please provide any information and copies along with the abstract.</VendorInstructions>
<VendorServices>
<TitleVendorService>
<TitleVendorServiceId>6615159</TitleVendorServiceId>
<ServiceCode>1OWNER</ServiceCode>
<CustomVendorInstructions><p><b>Copies of recital page, legal description and signature pages of all open mortgages must be provided including copies of the legal description and any riders.<br /> <br /> Copies of assignments must be provided for open liens.<br /> <br /> If the property is registered land a copy of the certificate of title must accompany the search</CustomVendorInstructions>
</TitleVendorService>
</VendorServices>
</TitleVendor>
</TitleVendors>
</Title>
</OrderTransaction>
</OrderTransactions>
[XmlArray("OrderTransactions")]
[XmlArrayItem("OrderTransaction")]
public List<OrderTransaction> OrderTransactions = new List<OrderTransaction>();
public class OrderTransaction
{
[XmlElement("LoanAmount")]
[DataMember]
public string LoanAmount { get; set; }
[XmlArray("Title")]
[XmlArrayItem("TitleVendors")]
public List<Title> Titles = new List<Title>();
public class Title
{
[XmlArray("TitleVendor")]
[XmlArrayItem("VendorInstructions")]
//[XmlArrayItem("VendorServices")]
public List<TitleVendor> TitleVendors = new List<TitleVendor>();
public class TitleVendor
{
[XmlElement("VendorInstructions")]
[DataMember]
public string VendorInstructions { get; set; }
[XmlArray("VendorServices")]
[XmlArrayItem("TitleVendorService")]
public List<VendorService> VendorServices = new List<VendorService>();
public class VendorService
{
public List<TitleVendorService> TitleVendorServices = new List<TitleVendorService>();
public class TitleVendorService
{
[XmlElement("TitleVendorServiceId")]
[DataMember]
public string TitleVendorServiceId { get; set; }
[XmlElement("ServiceCode")]
[DataMember]
public string ServiceCode { get; set; }
[XmlElement("CustomVendorInstructions")]
[DataMember]
public string CustomVendorInstructions { get; set; }
}
}
}
}
}
Related
I want to create an API in .net core which accept XML request and gives response in XML only.
I have searched and created sample but when I hit request to the API with XML request it does not work.
Debugger did not come up to the controller.
I have also added below the line of code in the configure services of the startup.cs class.
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
options.InputFormatters.Insert(0, new XDocumentInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
The POST method have written in the controller as below.
[Produces("application/xml")]
[ProducesResponseType(typeof(CustomerDetails), (int)HttpStatusCode.OK)]
[HttpPost("CustomerDetails", Name = "CustomerDetails")]
public IActionResult CustomerDetails([FromBody] CustomerDetails CustReq)
{
var resp = new CustomerDetails
{
BankId="1234567"
};
return Ok(resp);
}
Processing my request from Postman getting an error.
An unhandled exception occurred while processing the request.
InvalidCastException: Unable to cast object of type 'System.Xml.Linq.XDocument' to type 'CustomerValidationAPI.Models.CustomerDetails'.
Below is my XML request I want to process.
It also has multiple nodes how can we handle.
<?xml version="1.0" encoding="UTF-8"?>
<FIXML xmlns="http://www.finacle.com/fixml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.finacle.com/fixml
executeFinacleScript.xsd">
<Header>
<RequestHeader>
<MessageKey>
<RequestUUID>FEBA_1553756445880</RequestUUID>
<ServiceRequestId>executeFinacleScript</ServiceRequestId>
<ServiceRequestVersion>10.2</ServiceRequestVersion>
<ChannelId>COR</ChannelId>
</MessageKey>
<RequestMessageInfo>
<BankId>04</BankId>
<TimeZone>GMT+05:00</TimeZone>
<EntityId />
<EntityType />
<ArmCorrelationId />
<MessageDateTime>2019-03-28T11:00:45.880</MessageDateTime>
</RequestMessageInfo>
<Security>
<Token>
<PasswordToken>
<UserId>11111</UserId>
<Password />
</PasswordToken>
</Token>
<FICertToken />
<RealUserLoginSessionId />
<RealUser />
<RealUserPwd />
<SSOTransferToken />
</Security>
</RequestHeader>
</Header>
<Body>
<executeFinacleScriptRequest>
<ExecuteFinacleScriptInputVO>
<requestId>validateAcct.scr</requestId>
</ExecuteFinacleScriptInputVO>
<executeFinacleScript_CustomData>
<ACCT_NUM>01122507576</ACCT_NUM>
<PHONE_NUM>59887834</PHONE_NUM>
<NIC>G2105493001653</NIC>
</executeFinacleScript_CustomData>
</executeFinacleScriptRequest>
</Body>
</FIXML>
Customer Details Model Have created as below
public class CustomerDetails
{
[Required]
public string RequestUUID { get; set; }
[Required]
public string ServiceRequestId { get; set; }
[Required]
public string ServiceRequestVersion { get; set; }
[Required]
public string ChannelId { get; set; }
[Required]
public string BankId { get; set; }
[Required]
public string TimeZone { get; set; }
public string EntityId { get; set; }
public string EntityType { get; set; }
public string ArmCorrelationId { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime MessageDateTime { get; set; }
[Required]
public string Password { get; set; }
public string FICertToken { get; set; }
public string RealUserLoginSessionId { get; set; }
public string RealUser { get; set; }
public string RealUserPwd { get; set; }
public string SSOTransferToken { get; set; }
[Required]
public string requestId { get; set; }
[Required]
public string ACCT_NUM { get; set; }
[Required]
public string PHONE_NUM { get; set; }
[Required]
public string NIC { get; set; }
}
My startUp class
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
options.InputFormatters.Insert(0, new XDocumentInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
}
XDocumentInputFormatter in class have taken as below..
public class XDocumentInputFormatter : InputFormatter, IInputFormatter, IApiRequestFormatMetadataProvider
{
public XDocumentInputFormatter()
{
SupportedMediaTypes.Add("application/xml");
}
protected override bool CanReadType(Type type)
{
if (type.IsAssignableFrom(typeof(XDocument))) return true;
return base.CanReadType(type);
}
//public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
//{
// var xmlDoc = await XDocument.LoadAsync(context.HttpContext.Request.Body, LoadOptions.None, CancellationToken.None);
// return InputFormatterResult.Success(xmlDoc);
//}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
{
// Use StreamReader to convert any encoding to UTF-16 (default C# and sql Server).
using (var streamReader = new StreamReader(context.HttpContext.Request.Body))
{
var xmlDoc = await XDocument.LoadAsync(streamReader, LoadOptions.None, CancellationToken.None);
return InputFormatterResult.Success(xmlDoc);
}
}
}
ERROR I AM GETTING NOW
An unhandled exception occurred while processing the request.
InvalidOperationException: http://www.finacle.com/fixml'> was not expected.
Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderTestClass.Read3_TestClass()
InvalidOperationException: There is an error in XML document (1, 174).
System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events)
Created the Class from XML as below
public class XMLClass
{
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.finacle.com/fixml", IsNullable = false)]
public partial class FIXML
{
private FIXMLHeader headerField;
private FIXMLBody bodyField;
/// <remarks/>
public FIXMLHeader Header
{
get
{
return this.headerField;
}
set
{
this.headerField = value;
}
}
/// <remarks/>
public FIXMLBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeader
{
private FIXMLHeaderRequestHeader requestHeaderField;
/// <remarks/>
public FIXMLHeaderRequestHeader RequestHeader
{
get
{
return this.requestHeaderField;
}
set
{
this.requestHeaderField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeader
{
private FIXMLHeaderRequestHeaderMessageKey messageKeyField;
private FIXMLHeaderRequestHeaderRequestMessageInfo requestMessageInfoField;
private FIXMLHeaderRequestHeaderSecurity securityField;
/// <remarks/>
public FIXMLHeaderRequestHeaderMessageKey MessageKey
{
get
{
return this.messageKeyField;
}
set
{
this.messageKeyField = value;
}
}
/// <remarks/>
public FIXMLHeaderRequestHeaderRequestMessageInfo RequestMessageInfo
{
get
{
return this.requestMessageInfoField;
}
set
{
this.requestMessageInfoField = value;
}
}
/// <remarks/>
public FIXMLHeaderRequestHeaderSecurity Security
{
get
{
return this.securityField;
}
set
{
this.securityField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderMessageKey
{
private string requestUUIDField;
private string serviceRequestIdField;
private decimal serviceRequestVersionField;
private string channelIdField;
/// <remarks/>
public string RequestUUID
{
get
{
return this.requestUUIDField;
}
set
{
this.requestUUIDField = value;
}
}
/// <remarks/>
public string ServiceRequestId
{
get
{
return this.serviceRequestIdField;
}
set
{
this.serviceRequestIdField = value;
}
}
/// <remarks/>
public decimal ServiceRequestVersion
{
get
{
return this.serviceRequestVersionField;
}
set
{
this.serviceRequestVersionField = value;
}
}
/// <remarks/>
public string ChannelId
{
get
{
return this.channelIdField;
}
set
{
this.channelIdField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderRequestMessageInfo
{
private byte bankIdField;
private string timeZoneField;
private object entityIdField;
private object entityTypeField;
private object armCorrelationIdField;
private System.DateTime messageDateTimeField;
/// <remarks/>
public byte BankId
{
get
{
return this.bankIdField;
}
set
{
this.bankIdField = value;
}
}
/// <remarks/>
public string TimeZone
{
get
{
return this.timeZoneField;
}
set
{
this.timeZoneField = value;
}
}
/// <remarks/>
public object EntityId
{
get
{
return this.entityIdField;
}
set
{
this.entityIdField = value;
}
}
/// <remarks/>
public object EntityType
{
get
{
return this.entityTypeField;
}
set
{
this.entityTypeField = value;
}
}
/// <remarks/>
public object ArmCorrelationId
{
get
{
return this.armCorrelationIdField;
}
set
{
this.armCorrelationIdField = value;
}
}
/// <remarks/>
public System.DateTime MessageDateTime
{
get
{
return this.messageDateTimeField;
}
set
{
this.messageDateTimeField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderSecurity
{
private FIXMLHeaderRequestHeaderSecurityToken tokenField;
private object fICertTokenField;
private object realUserLoginSessionIdField;
private object realUserField;
private object realUserPwdField;
private object sSOTransferTokenField;
/// <remarks/>
public FIXMLHeaderRequestHeaderSecurityToken Token
{
get
{
return this.tokenField;
}
set
{
this.tokenField = value;
}
}
/// <remarks/>
public object FICertToken
{
get
{
return this.fICertTokenField;
}
set
{
this.fICertTokenField = value;
}
}
/// <remarks/>
public object RealUserLoginSessionId
{
get
{
return this.realUserLoginSessionIdField;
}
set
{
this.realUserLoginSessionIdField = value;
}
}
/// <remarks/>
public object RealUser
{
get
{
return this.realUserField;
}
set
{
this.realUserField = value;
}
}
/// <remarks/>
public object RealUserPwd
{
get
{
return this.realUserPwdField;
}
set
{
this.realUserPwdField = value;
}
}
/// <remarks/>
public object SSOTransferToken
{
get
{
return this.sSOTransferTokenField;
}
set
{
this.sSOTransferTokenField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderSecurityToken
{
private FIXMLHeaderRequestHeaderSecurityTokenPasswordToken passwordTokenField;
/// <remarks/>
public FIXMLHeaderRequestHeaderSecurityTokenPasswordToken PasswordToken
{
get
{
return this.passwordTokenField;
}
set
{
this.passwordTokenField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLHeaderRequestHeaderSecurityTokenPasswordToken
{
private ushort userIdField;
private object passwordField;
/// <remarks/>
public ushort UserId
{
get
{
return this.userIdField;
}
set
{
this.userIdField = value;
}
}
/// <remarks/>
public object Password
{
get
{
return this.passwordField;
}
set
{
this.passwordField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLBody
{
private FIXMLBodyExecuteFinacleScriptRequest executeFinacleScriptRequestField;
/// <remarks/>
public FIXMLBodyExecuteFinacleScriptRequest executeFinacleScriptRequest
{
get
{
return this.executeFinacleScriptRequestField;
}
set
{
this.executeFinacleScriptRequestField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLBodyExecuteFinacleScriptRequest
{
private FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO executeFinacleScriptInputVOField;
private FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData executeFinacleScript_CustomDataField;
/// <remarks/>
public FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO ExecuteFinacleScriptInputVO
{
get
{
return this.executeFinacleScriptInputVOField;
}
set
{
this.executeFinacleScriptInputVOField = value;
}
}
/// <remarks/>
public FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData executeFinacleScript_CustomData
{
get
{
return this.executeFinacleScript_CustomDataField;
}
set
{
this.executeFinacleScript_CustomDataField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScriptInputVO
{
private string requestIdField;
/// <remarks/>
public string requestId
{
get
{
return this.requestIdField;
}
set
{
this.requestIdField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.finacle.com/fixml")]
public partial class FIXMLBodyExecuteFinacleScriptRequestExecuteFinacleScript_CustomData
{
private uint aCCT_NUMField;
private uint pHONE_NUMField;
private string nICField;
/// <remarks/>
public uint ACCT_NUM
{
get
{
return this.aCCT_NUMField;
}
set
{
this.aCCT_NUMField = value;
}
}
/// <remarks/>
public uint PHONE_NUM
{
get
{
return this.pHONE_NUMField;
}
set
{
this.pHONE_NUMField = value;
}
}
/// <remarks/>
public string NIC
{
get
{
return this.nICField;
}
set
{
this.nICField = value;
}
}
}
}
public class Token
{
public PasswordToken PasswordToken{get;set;}
}
public class PasswordToken
{
public string UserId{get;set;}
public string Password{get;set;}
}
public class Body
{
public executeFinacleScriptRequest executeFinacleScriptRequest{get;set;}
}
public class executeFinacleScriptRequest
{
public ExecuteFinacleScriptInputVO ExecuteFinacleScriptInputVO{get;set;}
public executeFinacleScript_CustomData executeFinacleScript_CustomData{get;set;}
}
public class ExecuteFinacleScriptInputVO
{
public string requestId{get;set;}
}
public class executeFinacleScript_CustomData
{
public string ACCT_NUM{get;set;}
public string PHONE_NUM{get;set;}
public string NIC{get;set;}
}
the result is serialized based on what the requester requested! if you want xml just put ja corresponding header! and why [FromBody]XElement xml ? cant you use a normal model?
If Your API need request in XML. Below are things need to consider
1. In .ent core add below code in ConfigureServices method of Startup.cs Class
services.AddMvc(options =>
{
options.RespectBrowserAcceptHeader = true; // false by default
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddXmlSerializerFormatters()
.AddXmlDataContractSerializerFormatters();
Create XML Data class by just simply copy your XML request and in the visual studio ..select paste special from edit menu and select paste XML as classes. It will generate classes as per your XML.
Now you this class as [FromBody] YourClassName request in post method. Do include produce annotation as application/xml above your post method
In ASP.NET Core, everything is highly modular, so you only add the functionality you need to your application. Consequently, there's a separate NuGet package for the XML formatters that you need to add to your .csproj file - Microsoft.AspNetCore.Mvc.Formatters.Xml
<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Xml" Version="1.1.3" />
Adding the package to your project lights up an extension method on the IMvcBuilder instance returned by the call to services.AddMvc(). The AddXmlSerializerFormatters() method adds both input and output formatters, so you can serialise objects to and from XML.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddXmlSerializerFormatters();
}
Alternatively, if you only want to be able to format results as XML, but don't need to be able to read XML from a request body, you can just add the output formatter instead:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});
}
For Supporting XML as Input
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.FormatterMappings.SetMediaTypeMappingForFormat
("xml", MediaTypeHeaderValue.Parse("application/xml"));
options.FormatterMappings.SetMediaTypeMappingForFormat
("config", MediaTypeHeaderValue.Parse("application/xml"));
options.FormatterMappings.SetMediaTypeMappingForFormat
("js", MediaTypeHeaderValue.Parse("application/json"));
})
.AddXmlSerializerFormatters();
I am trying to deserialize the following XML
<?xml version="1.0" encoding="UTF-8"?>
<GovTalkMessage xmlns="http://www.govtalk.gov.uk/CM/envelope">
<EnvelopeVersion>2.0</EnvelopeVersion>
<Header>
<MessageDetails>
<Class>DRUG_DATA</Class>
<Qualifier>response</Qualifier>
<Function>submit</Function>
<CorrelationID>BD694DAAA26AA6068EAAAE5C7746CE54</CorrelationID>
<Transformation>XML</Transformation>
</MessageDetails>
<SenderDetails>
<IDAuthentication>
<SenderID />
<Authentication>
<Method />
<Role />
<Value />
</Authentication>
</IDAuthentication>
</SenderDetails>
</Header>
<GovTalkDetails>
<Keys>
<Key Type="SpokeName" />
</Keys>
</GovTalkDetails>
<Body>
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">
<S:Body>
<ns2:getGenericDrugsResponse xmlns:ns2="http://webservice.sirkb/">
<return>
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
<GENERIC_DRUG_ID>147</GENERIC_DRUG_ID>
<GENERIC_DRUG_NAME>Amoxicilline 125mg/5ml - 60ml</GENERIC_DRUG_NAME>
</DRUG>
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
<GENERIC_DRUG_ID>149</GENERIC_DRUG_ID>
<GENERIC_DRUG_NAME>Amoxicilline 250mg/5ml - 60ml</GENERIC_DRUG_NAME>
</DRUG>
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
<DOSAGE>10mg/5ml</DOSAGE>
<GENERIC_DRUG_ID>2312</GENERIC_DRUG_ID>
<GENERIC_DRUG_NAME>Vinorelbine (as vinorelbine tartrate)</GENERIC_DRUG_NAME>
<PHARMACEUTICAL_FORM>concentrate for solution for infusion</PHARMACEUTICAL_FORM>
</DRUG>
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
<DOSAGE>100 u/ml (approximately 0.58mg)</DOSAGE>
<GENERIC_DRUG_ID>2313</GENERIC_DRUG_ID>
<GENERIC_DRUG_NAME>Laronidase</GENERIC_DRUG_NAME>
<PHARMACEUTICAL_FORM>concentrate for solution for infusion</PHARMACEUTICAL_FORM>
</DRUG>
<RETURN_STATUS>SUCCESS</RETURN_STATUS>
</return>
</ns2:getGenericDrugsResponse>
</S:Body>
</S:Envelope>
</Body>
</GovTalkMessage>
I have generated the classes through Paste XML as Classes feature of Visual Studio 2017. (Using the xsd.exe is the same) I have not changed the generated classes.
They have the following form:
// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope", IsNullable = false)]
public partial class GovTalkMessage
{
private decimal envelopeVersionField;
private GovTalkMessageHeader headerField;
private GovTalkMessageGovTalkDetails govTalkDetailsField;
private GovTalkMessageBody bodyField;
/// <remarks/>
public decimal EnvelopeVersion
{
get
{
return this.envelopeVersionField;
}
set
{
this.envelopeVersionField = value;
}
}
/// <remarks/>
public GovTalkMessageHeader Header
{
get
{
return this.headerField;
}
set
{
this.headerField = value;
}
}
/// <remarks/>
public GovTalkMessageGovTalkDetails GovTalkDetails
{
get
{
return this.govTalkDetailsField;
}
set
{
this.govTalkDetailsField = value;
}
}
/// <remarks/>
public GovTalkMessageBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeader
{
private GovTalkMessageHeaderMessageDetails messageDetailsField;
private GovTalkMessageHeaderSenderDetails senderDetailsField;
/// <remarks/>
public GovTalkMessageHeaderMessageDetails MessageDetails
{
get
{
return this.messageDetailsField;
}
set
{
this.messageDetailsField = value;
}
}
/// <remarks/>
public GovTalkMessageHeaderSenderDetails SenderDetails
{
get
{
return this.senderDetailsField;
}
set
{
this.senderDetailsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeaderMessageDetails
{
private string classField;
private string qualifierField;
private string functionField;
private string correlationIDField;
private string transformationField;
/// <remarks/>
public string Class
{
get
{
return this.classField;
}
set
{
this.classField = value;
}
}
/// <remarks/>
public string Qualifier
{
get
{
return this.qualifierField;
}
set
{
this.qualifierField = value;
}
}
/// <remarks/>
public string Function
{
get
{
return this.functionField;
}
set
{
this.functionField = value;
}
}
/// <remarks/>
public string CorrelationID
{
get
{
return this.correlationIDField;
}
set
{
this.correlationIDField = value;
}
}
/// <remarks/>
public string Transformation
{
get
{
return this.transformationField;
}
set
{
this.transformationField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeaderSenderDetails
{
private GovTalkMessageHeaderSenderDetailsIDAuthentication iDAuthenticationField;
/// <remarks/>
public GovTalkMessageHeaderSenderDetailsIDAuthentication IDAuthentication
{
get
{
return this.iDAuthenticationField;
}
set
{
this.iDAuthenticationField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeaderSenderDetailsIDAuthentication
{
private object senderIDField;
private GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication authenticationField;
/// <remarks/>
public object SenderID
{
get
{
return this.senderIDField;
}
set
{
this.senderIDField = value;
}
}
/// <remarks/>
public GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication Authentication
{
get
{
return this.authenticationField;
}
set
{
this.authenticationField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageHeaderSenderDetailsIDAuthenticationAuthentication
{
private object methodField;
private object roleField;
private object valueField;
/// <remarks/>
public object Method
{
get
{
return this.methodField;
}
set
{
this.methodField = value;
}
}
/// <remarks/>
public object Role
{
get
{
return this.roleField;
}
set
{
this.roleField = value;
}
}
/// <remarks/>
public object Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageGovTalkDetails
{
private GovTalkMessageGovTalkDetailsKeys keysField;
/// <remarks/>
public GovTalkMessageGovTalkDetailsKeys Keys
{
get
{
return this.keysField;
}
set
{
this.keysField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageGovTalkDetailsKeys
{
private GovTalkMessageGovTalkDetailsKeysKey keyField;
/// <remarks/>
public GovTalkMessageGovTalkDetailsKeysKey Key
{
get
{
return this.keyField;
}
set
{
this.keyField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageGovTalkDetailsKeysKey
{
private string typeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class GovTalkMessageBody
{
private Envelope envelopeField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.w3.org/2003/05/soap-envelope")]
public Envelope Envelope
{
get
{
return this.envelopeField;
}
set
{
this.envelopeField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2003/05/soap-envelope")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.w3.org/2003/05/soap-envelope", IsNullable = false)]
public partial class Envelope
{
private EnvelopeBody bodyField;
/// <remarks/>
public EnvelopeBody Body
{
get
{
return this.bodyField;
}
set
{
this.bodyField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.w3.org/2003/05/soap-envelope")]
public partial class EnvelopeBody
{
private getGenericDrugsResponse getGenericDrugsResponseField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://webservice.sirkb/")]
public getGenericDrugsResponse getGenericDrugsResponse
{
get
{
return this.getGenericDrugsResponseField;
}
set
{
this.getGenericDrugsResponseField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://webservice.sirkb/")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://webservice.sirkb/", IsNullable = false)]
public partial class getGenericDrugsResponse
{
private #return returnField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public #return #return
{
get
{
return this.returnField;
}
set
{
this.returnField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope", IsNullable = false)]
public partial class #return
{
private returnDRUG[] dRUGField;
private string rETURN_STATUSField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("DRUG")]
public returnDRUG[] DRUG
{
get
{
return this.dRUGField;
}
set
{
this.dRUGField = value;
}
}
/// <remarks/>
public string RETURN_STATUS
{
get
{
return this.rETURN_STATUSField;
}
set
{
this.rETURN_STATUSField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class returnDRUG
{
private string dOSAGEField;
private ushort gENERIC_DRUG_IDField;
private string gENERIC_DRUG_NAMEField;
private string pHARMACEUTICAL_FORMField;
/// <remarks/>
public string DOSAGE
{
get
{
return this.dOSAGEField;
}
set
{
this.dOSAGEField = value;
}
}
/// <remarks/>
public ushort GENERIC_DRUG_ID
{
get
{
return this.gENERIC_DRUG_IDField;
}
set
{
this.gENERIC_DRUG_IDField = value;
}
}
/// <remarks/>
public string GENERIC_DRUG_NAME
{
get
{
return this.gENERIC_DRUG_NAMEField;
}
set
{
this.gENERIC_DRUG_NAMEField = value;
}
}
/// <remarks/>
public string PHARMACEUTICAL_FORM
{
get
{
return this.pHARMACEUTICAL_FORMField;
}
set
{
this.pHARMACEUTICAL_FORMField = value;
}
}
}
I get the following error:
System.InvalidOperationException: 'There is an error in XML document (33, 14).'
Inner Exception
InvalidOperationException: The specified type was not recognized:
name='genericDrug', namespace='http://webservice.sirkb/', at http://www.govtalk.gov.uk/CM/envelope'>.
I have noticed from this thread that if I remove xsi:type="ns2:genericDrug" from the XML file I can deserialize the XML. I can't modify the XML because it is the response I get for the request. It is not a good practice to do a string replace on XML, so I am looking for a better solution.
This might be a duplicate question from this one, but since I am not able to solve the problem I am posting it again because it is difficult to get help in the comment section.
Based on the above question I have tried to change the annotation of public partial class returnDRUG
from
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
to
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://www.w3.org/2001/XMLSchema-instance", TypeName = "genericDrug")]
but still cant parse the XML.
The parsing code is simple
var deserializer = new XmlSerializer(typeof(GovTalkMessage));
TextReader textReader = new StreamReader("drug.xml"); //saved response in file for simplicity
GovTalkMessage response;
response = (GovTalkMessage)deserializer.Deserialize(textReader);
textReader.Close();
What can I do to deserialize the XML in the GovTalkMessage object?
You need to change the decoration on the returnDRUG class
from this
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public partial class returnDRUG
to this
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "genericDrug", Namespace = "http://webservice.sirkb/")]
public partial class returnDRUG
Specify it's type as "genericDrug", and the crucial bit, correct it's namespace to "http://webservice.sirkb/"
I've just used you code and managed to de-serialize using this change.
The explanation is that if you take a look at the definition of DRUG you can see that it's type is defined as "genericDRUG" in the namespace alias "ns2"
<DRUG xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns2:genericDrug">
if you look at the definition of the ns2 alias you can see that it's "http://webservice.sirkb/"
<ns2:getGenericDrugsResponse xmlns:ns2="http://webservice.sirkb/">
Some addition to prevent default values for DRUG objects
Every property of the returnDrug class should have the namespace http://www.govtalk.gov.uk/CM/envelope.
The complete class should have the following form:
[System.Xml.Serialization.XmlTypeAttribute(TypeName = "genericDrug", Namespace = "http://webservice.sirkb/")]
public partial class returnDRUG
{
private string dOSAGEField;
private ushort gENERIC_DRUG_IDField;
private string gENERIC_DRUG_NAMEField;
private string pHARMACEUTICAL_FORMField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public string DOSAGE
{
get
{
return this.dOSAGEField;
}
set
{
this.dOSAGEField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public ushort GENERIC_DRUG_ID
{
get
{
return this.gENERIC_DRUG_IDField;
}
set
{
this.gENERIC_DRUG_IDField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public string GENERIC_DRUG_NAME
{
get
{
return this.gENERIC_DRUG_NAMEField;
}
set
{
this.gENERIC_DRUG_NAMEField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "http://www.govtalk.gov.uk/CM/envelope")]
public string PHARMACEUTICAL_FORM
{
get
{
return this.pHARMACEUTICAL_FORMField;
}
set
{
this.pHARMACEUTICAL_FORMField = value;
}
}
}
I have below XML and need to deserialized to get the value of "ThreadGroup.num_threads","ThreadGroup.ramp_time","HTTPSampler.path" and "HTTPSampler.domain".
<TestPlan>
<hashTree>
<hashTree>
<ThreadGroup>
<stringProp name="ThreadGroup.on_sample_error">continue</stringProp>
<stringProp name="ThreadGroup.num_threads">10</stringProp>
<stringProp name="ThreadGroup.ramp_time">1</stringProp>
<longProp name="ThreadGroup.start_time">1517853259000</longProp>
<longProp name="ThreadGroup.end_time">1517853259000</longProp>
<boolProp name="ThreadGroup.scheduler">false</boolProp>
<stringProp name="ThreadGroup.duration"></stringProp>
<stringProp name="ThreadGroup.delay"></stringProp>
</ThreadGroup>
<hashTree>
<hashTree>
<HTTPSamplerProxy>
<stringProp name="HTTPSampler.domain">www.abc.com/abc-service-api</stringProp>
<stringProp name="HTTPSampler.port"></stringProp>
<stringProp name="HTTPSampler.protocol"></stringProp>
<stringProp name="HTTPSampler.contentEncoding"></stringProp>
<stringProp name="HTTPSampler.path">/v1/test/test?debug=false</stringProp>
<stringProp name="HTTPSampler.method">GET</stringProp>
<boolProp name="HTTPSampler.follow_redirects">false</boolProp>
<boolProp name="HTTPSampler.auto_redirects">false</boolProp>
<boolProp name="HTTPSampler.use_keepalive">true</boolProp>
<boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
<stringProp name="HTTPSampler.embedded_url_re"></stringProp>
<stringProp name="HTTPSampler.connect_timeout"></stringProp>
<stringProp name="HTTPSampler.response_timeout"></stringProp>
</HTTPSamplerProxy>
</hashTree>
</hashTree>
</hashTree>
</hashTree>
</TestPlan>
The code I am using mentioned below.
public class xmlData
{
[Serializable, XmlRoot("jmeterTestPlan")]
public partial class jmeterTestPlan
{
private jmeterTestPlanHashTree hashTreeField;
/// <remarks/>
public jmeterTestPlanHashTree hashTree
{
get
{
return this.hashTreeField;
}
set
{
this.hashTreeField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTree
{
private jmeterTestPlanHashTreeHashTree hashTreeField;
/// <remarks/>
public jmeterTestPlanHashTreeHashTree hashTree
{
get
{
return this.hashTreeField;
}
set
{
this.hashTreeField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTree
{
private jmeterTestPlanHashTreeHashTreeThreadGroup threadGroupField;
private jmeterTestPlanHashTreeHashTreeHashTree hashTreeField;
/// <remarks/>
public jmeterTestPlanHashTreeHashTreeThreadGroup ThreadGroup
{
get
{
return this.threadGroupField;
}
set
{
this.threadGroupField = value;
}
}
/// <remarks/>
public jmeterTestPlanHashTreeHashTreeHashTree hashTree
{
get
{
return this.hashTreeField;
}
set
{
this.hashTreeField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeThreadGroup
{
private object[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("boolProp", typeof(jmeterTestPlanHashTreeHashTreeThreadGroupBoolProp))]
[System.Xml.Serialization.XmlElementAttribute("longProp", typeof(jmeterTestPlanHashTreeHashTreeThreadGroupLongProp))]
[System.Xml.Serialization.XmlElementAttribute("stringProp", typeof(jmeterTestPlanHashTreeHashTreeThreadGroupStringProp))]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeThreadGroupBoolProp
{
private string nameField;
private bool valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public bool Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeThreadGroupLongProp
{
private string nameField;
private ulong valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public ulong Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeThreadGroupStringProp
{
private string nameField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeHashTree
{
private jmeterTestPlanHashTreeHashTreeHashTreeHashTree hashTreeField;
/// <remarks/>
public jmeterTestPlanHashTreeHashTreeHashTreeHashTree hashTree
{
get
{
return this.hashTreeField;
}
set
{
this.hashTreeField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeHashTreeHashTree
{
private jmeterTestPlanHashTreeHashTreeHashTreeHashTreeHTTPSamplerProxy hTTPSamplerProxyField;
/// <remarks/>
public jmeterTestPlanHashTreeHashTreeHashTreeHashTreeHTTPSamplerProxy HTTPSamplerProxy
{
get
{
return this.hTTPSamplerProxyField;
}
set
{
this.hTTPSamplerProxyField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeHashTreeHashTreeHTTPSamplerProxy
{
private object[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("boolProp", typeof(jmeterTestPlanHashTreeHashTreeHashTreeHashTreeHTTPSamplerProxyBoolProp))]
[System.Xml.Serialization.XmlElementAttribute("stringProp", typeof(jmeterTestPlanHashTreeHashTreeHashTreeHashTreeHTTPSamplerProxyStringProp))]
public object[] Items
{
get
{
return this.itemsField;
}
set
{
this.itemsField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeHashTreeHashTreeHTTPSamplerProxyBoolProp
{
private string nameField;
private bool valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public bool Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class jmeterTestPlanHashTreeHashTreeHashTreeHashTreeHTTPSamplerProxyStringProp
{
private string nameField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name
{
get
{
return this.nameField;
}
set
{
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
}
the above code is giving required value with a lot of additional attributes value and the code seems lengthy too. However, I need those 4 value. Please suggest any better solution.
UPDATED (2018-09-10)
I've updated this to get it easy to use.
Before I started, I decided that you probably wanted the possibility of longProps in the HTTPSamplerProxy section. It also made the coding (much) easier and cleaner. I've tested it without any longProps just to make sure it worked with the existing XML the way you'd expect.
The original process
The updates to the original description are italicized
What I did was to use the standard XSD.exe tool to take your source XML file (with an extra longProp in the HTTPSamplerProxy section) and create an XSD. Then I used XSD.exe again to create a (very ugly) C# file. At that point, the root of the whole mess is the TestPlan class. Here's what XSD.exe produced (updated - the only change to the newly-emitted XSD.exe code was a namespace declaration at the top):
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class hashTree {
private hashTreeHTTPSamplerProxy[] hTTPSamplerProxyField;
private hashTree[] hashTree1Field;
private hashTreeThreadGroup[] threadGroupField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("HTTPSamplerProxy", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public hashTreeHTTPSamplerProxy[] HTTPSamplerProxy {
get {
return this.hTTPSamplerProxyField;
}
set {
this.hTTPSamplerProxyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("hashTree")]
public hashTree[] hashTree1 {
get {
return this.hashTree1Field;
}
set {
this.hashTree1Field = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ThreadGroup", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public hashTreeThreadGroup[] ThreadGroup {
get {
return this.threadGroupField;
}
set {
this.threadGroupField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class hashTreeHTTPSamplerProxy {
private longProp[] longPropField;
private stringProp[] stringPropField;
private boolProp[] boolPropField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("longProp", IsNullable = true)]
public longProp[] longProp {
get {
return this.longPropField;
}
set {
this.longPropField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("stringProp", IsNullable = true)]
public stringProp[] stringProp {
get {
return this.stringPropField;
}
set {
this.stringPropField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("boolProp", IsNullable = true)]
public boolProp[] boolProp {
get {
return this.boolPropField;
}
set {
this.boolPropField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public partial class longProp {
private string nameField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public partial class stringProp {
private string nameField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = true)]
public partial class boolProp {
private string nameField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class hashTreeThreadGroup {
private stringProp[] stringPropField;
private longProp[] longPropField;
private boolProp[] boolPropField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("stringProp", IsNullable = true)]
public stringProp[] stringProp {
get {
return this.stringPropField;
}
set {
this.stringPropField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("longProp", IsNullable = true)]
public longProp[] longProp {
get {
return this.longPropField;
}
set {
this.longPropField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("boolProp", IsNullable = true)]
public boolProp[] boolProp {
get {
return this.boolPropField;
}
set {
this.boolPropField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class TestPlan {
private object[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("boolProp", typeof(boolProp), IsNullable = true)]
[System.Xml.Serialization.XmlElementAttribute("hashTree", typeof(hashTree))]
[System.Xml.Serialization.XmlElementAttribute("longProp", typeof(longProp), IsNullable = true)]
[System.Xml.Serialization.XmlElementAttribute("stringProp", typeof(stringProp), IsNullable = true)]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
The rest of this is mostly new
The code emitted by XSD.exe creates a set of partial classes. I extended the partial classes in a few ways in a separate source file. But, before I started, I declared an interface and a static worker class.
public interface IGrouping {
boolProp[] boolProp { get; }
stringProp[] stringProp { get; }
longProp[] longProp { get; }
Dictionary<string, bool?> BoolProperties { get; }
Dictionary<string, long?> LongProperties { get; }
Dictionary<string, string> StringProperties { get; }
}
and
public static class PropertyGrouper {
public static void GroupProperties(IGrouping itemToGroup) {
//has this been done before, if yes, return
if (itemToGroup.StringProperties.Count > 0 || itemToGroup.BoolProperties.Count > 0 || itemToGroup.LongProperties.Count > 0 ) {
return;
}
//otherwise
if (itemToGroup.boolProp != null) {
foreach (var bProp in itemToGroup.boolProp) {
var succeeded = bool.TryParse(bProp.Value, out var bValue);
itemToGroup.BoolProperties.Add(bProp.name, succeeded ? bValue : (bool?)null);
}
}
if (itemToGroup.longProp != null) {
foreach (var lProp in itemToGroup.longProp) {
var succeeded = long.TryParse(lProp.Value, out var lValue);
itemToGroup.LongProperties.Add(lProp.name, succeeded ? lValue : (long?)null);
}
}
if (itemToGroup.stringProp != null) {
foreach (var sProp in itemToGroup.stringProp) {
itemToGroup.StringProperties.Add(sProp.name, sProp.Value);
}
}
}
}
With those in place, I extended each of the XSD.exe-emitted classes. The TestPlan class was easy - I just added a typed property:
public partial class TestPlan {
[XmlIgnore]
public hashTree HashTree => Items[0] as hashTree;
}
The hashTreeThreadGroup and hashTreeHTTPSamplerProxy classes were extended in the same way (remember, I didn't name any of these classes, XSD.exe named them from your XML) . Each was declared to implement the IGrouping interface, and each got 3 dictionaries of properties (as required by IGrouping). The three arrays in the IGrouping interface were in the XSD-emitted code:
public partial class hashTreeThreadGroup : IGrouping {
[XmlIgnore]
public Dictionary<string, bool?> BoolProperties { get; } = new Dictionary<string, bool?>();
[XmlIgnore]
public Dictionary<string, long?> LongProperties { get; } = new Dictionary<string, long?>();
[XmlIgnore]
public Dictionary<string, string> StringProperties { get; } = new Dictionary<string, string>();
}
public partial class hashTreeHTTPSamplerProxy : IGrouping {
[XmlIgnore]
public Dictionary<string, bool?> BoolProperties { get; } = new Dictionary<string, bool?>();
[XmlIgnore]
public Dictionary<string, long?> LongProperties { get; } = new Dictionary<string, long?>();
[XmlIgnore]
public Dictionary<string, string> StringProperties { get; } = new Dictionary<string, string>();
}
Finally, I extended hashTree class. I added three typed properties, each with a null check to make things clean. The ThreadGroupItem and HttpSamplerProxyItem properties each get a call to PropertyGrouper.GroupProperties. The first time this is called, the properties in the XmlSerializer-created property arrays are copied into Dictionaries.
public partial class hashTree {
[XmlIgnore]
public hashTree HashTree {
get {
if (hashTree1 != null) {
return hashTree1[0] as hashTree;
} else {
return null;
}
}
}
[XmlIgnore]
public hashTreeThreadGroup ThreadGroupItem {
get {
if (ThreadGroup != null) {
var threadGroup = ThreadGroup[0]; // as hashTreeThreadGroup;
PropertyGrouper.GroupProperties(threadGroup);
return threadGroup;
} else {
return null;
}
}
}
[XmlIgnore]
public hashTreeHTTPSamplerProxy HttpSamplerProxyItem {
get {
if (HTTPSamplerProxy != null) {
var httpSamplerProxy = HTTPSamplerProxy[0];
PropertyGrouper.GroupProperties(httpSamplerProxy);
return httpSamplerProxy;
} else {
return null;
}
}
}
}
With that all in place, I ran the same code.
TestPlan result;
using (var stream = new FileStream("source.xml", FileMode.Open, FileAccess.Read)) {
var serializer = new XmlSerializer(typeof(TestPlan));
result = (TestPlan)serializer.Deserialize(stream);
}
This code is how I accessed your data with my first example.
var numThreadsParsed = long.TryParse((((XmlSerializeForm.hashTree)result.Items[0]).hashTree1[0].ThreadGroup[0].stringProp[1].Value), out var numThreads);
var httpSamplerPath = ((XmlSerializeForm.hashTree)result.Items[0]).hashTree1[0].hashTree1[0].hashTree1[0].HTTPSamplerProxy[0].stringProp[4].Value;
But, with the few simple additions I made (well, the code isn't that complicated, but getting it right was), accessing the properties is much cleaner:
string numThreadsParsed = result.HashTree.HashTree.ThreadGroupItem.StringProperties["ThreadGroup.num_threads"];
long? startTime = result.HashTree.HashTree.ThreadGroupItem.LongProperties["ThreadGroup.start_time"];
string httpSamplerPath = result.HashTree.HashTree.HashTree.HashTree.HttpSamplerProxyItem.StringProperties["HTTPSampler.path"];
bool? useKeepAlive = result.HashTree.HashTree.HashTree.HashTree.HttpSamplerProxyItem.BoolProperties["HTTPSampler.use_keepalive"];
There you go!
With external lib Cinchoo ETL - an open source library, you can grab the chosen node values easily as below
Define .NET type
public class TestPlan
{
[ChoXmlNodeRecordField(XPath = #"/ThreadGroup/stringProp[#name=""ThreadGroup.on_sample_error""]")]
public string NumThreads { get; set; }
[ChoXmlNodeRecordField(XPath = #"/ThreadGroup/stringProp[#name=""ThreadGroup.ramp_time""]")]
public int RampTime { get; set; }
[ChoXmlNodeRecordField(XPath = #"/hashTree/hashTree/HTTPSamplerProxy/stringProp[#name=""HTTPSampler.path""]")]
public string Path { get; set; }
[ChoXmlNodeRecordField(XPath = #"/hashTree/hashTree/HTTPSamplerProxy/stringProp[#name=""HTTPSampler.domain""]")]
public string Domain { get; set; }
}
Then deserialize the input xml using Cinchoo ETL as below
static void Main()
{
using (var p = new ChoXmlReader<TestPlan>("*** XML file path ***")
.WithXPath("/TestPlan/hashTree/hashTree")
)
{
foreach (var rec in p)
Console.WriteLine(rec.Dump());
}
}
Output:
-- ChoXmlReaderTest.Program+TestPlan State --
NumThreads: continue
RampTime: 1
Path: /v1/test/test?debug=false
Domain: www.abc.com/abc-service-api
Hope it helps.
Disclaimer: I'm the author of this library.
Use xml linq :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlData data = new XmlData(FILENAME);
}
}
public class XmlData
{
public int? num_threads { get; set;}
public int? ramp_time { get;set;}
List<SamplerProxy> HTTPSamplerProxies { get;set;}
public XmlData(string filename)
{
XDocument doc = XDocument.Load(filename);
XElement threadGroup = doc.Descendants("ThreadGroup").FirstOrDefault();
num_threads = (int?)threadGroup.Elements("stringProp").Where(x => (string)x.Attribute("name") == "ThreadGroup.num_threads").FirstOrDefault();
ramp_time = (int?)threadGroup.Elements("stringProp").Where(x => (string)x.Attribute("name") == "ThreadGroup.ramp_time").FirstOrDefault();
HTTPSamplerProxies = doc.Descendants("HTTPSamplerProxy").Select(x => new SamplerProxy() {
path = (string)x.Elements("stringProp").Where(y => (string)y.Attribute("name") == "HTTPSampler.path").FirstOrDefault(),
domain = (string)x.Elements("stringProp").Where(y => (string)y.Attribute("name") == "HTTPSampler.domain").FirstOrDefault()
}).ToList();
}
}
public class SamplerProxy
{
public string path { get; set; }
public string domain { get; set; }
}
}
I've generated a xsd file from xml and then priceResponse.cs from xsd file using xsd.exe.
Here is priceResponse.cs code:
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.6.1055.0.
//
/// <uwagi/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class document {
private object[] itemsField;
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute("DATASETS", typeof(documentDATASETS), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlElementAttribute("ERROR", typeof(documentERROR), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
[System.Xml.Serialization.XmlElementAttribute("PRICE", typeof(documentPRICE), Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
/// <uwagi/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class documentDATASETS {
private string cOUNTRYField;
private string cURRENCYField;
private string pOSTCODEMASKField;
private string tOWNGROUPField;
private string sERVICEField;
private string oPTIONField;
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string COUNTRY {
get {
return this.cOUNTRYField;
}
set {
this.cOUNTRYField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CURRENCY {
get {
return this.cURRENCYField;
}
set {
this.cURRENCYField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string POSTCODEMASK {
get {
return this.pOSTCODEMASKField;
}
set {
this.pOSTCODEMASKField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string TOWNGROUP {
get {
return this.tOWNGROUPField;
}
set {
this.tOWNGROUPField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string SERVICE {
get {
return this.sERVICEField;
}
set {
this.sERVICEField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OPTION {
get {
return this.oPTIONField;
}
set {
this.oPTIONField = value;
}
}
}
/// <uwagi/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class documentERROR {
private string cODEField;
private string dESCRIPTIONField;
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CODE {
get {
return this.cODEField;
}
set {
this.cODEField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string DESCRIPTION {
get {
return this.dESCRIPTIONField;
}
set {
this.dESCRIPTIONField = value;
}
}
}
/// <uwagi/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class documentPRICE {
private string rATEIDField;
private string sERVICEField;
private string sERVICEDESCField;
private string oPTIONField;
private string oPTIONDESCField;
private string cURRENCYField;
private string rATEField;
private string rESULTField;
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string RATEID {
get {
return this.rATEIDField;
}
set {
this.rATEIDField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string SERVICE {
get {
return this.sERVICEField;
}
set {
this.sERVICEField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string SERVICEDESC {
get {
return this.sERVICEDESCField;
}
set {
this.sERVICEDESCField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OPTION {
get {
return this.oPTIONField;
}
set {
this.oPTIONField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string OPTIONDESC {
get {
return this.oPTIONDESCField;
}
set {
this.oPTIONDESCField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string CURRENCY {
get {
return this.cURRENCYField;
}
set {
this.cURRENCYField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string RATE {
get {
return this.rATEField;
}
set {
this.rATEField = value;
}
}
/// <uwagi/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string RESULT {
get {
return this.rESULTField;
}
set {
this.rESULTField = value;
}
}
}
I'm trying to deserialize priceResponse.xml but It seems like it is stuck. I think there is problem with namespaces and I'm doing deserialization wrong.
Here is xml code:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<document>
<DATASETS>
<COUNTRY>UTD</COUNTRY>
<CURRENCY>UTD</CURRENCY>
<POSTCODEMASK>UTD</POSTCODEMASK>
<TOWNGROUP>UTD</TOWNGROUP>
<SERVICE>UTD</SERVICE>
<OPTION>UTD</OPTION>
</DATASETS>
<ERROR>
<CODE>P13</CODE>
<DESCRIPTION>RATEID: 1 - Standard Rates</DESCRIPTION>
</ERROR>
<PRICE>
<RATEID>1</RATEID>
<SERVICE>09N</SERVICE>
<SERVICEDESC>9:00 Express</SERVICEDESC>
<OPTION>NONE</OPTION>
<OPTIONDESC>NONE</OPTIONDESC>
<CURRENCY>PLN</CURRENCY>
<RATE>712.93</RATE>
<RESULT>Y</RESULT>
</PRICE>
<PRICE>
<RATEID>1</RATEID>
<SERVICE>10N</SERVICE>
<SERVICEDESC>10:00 Express</SERVICEDESC>
<OPTION>NONE</OPTION>
<OPTIONDESC>NONE</OPTIONDESC>
<CURRENCY>PLN</CURRENCY>
<RATE>706.14</RATE>
<RESULT>Y</RESULT>
</PRICE>
<PRICE>
<RATEID>1</RATEID>
<SERVICE>12N</SERVICE>
<SERVICEDESC>12:00 Express</SERVICEDESC>
<OPTION>NONE</OPTION>
<OPTIONDESC>NONE</OPTIONDESC>
<CURRENCY>PLN</CURRENCY>
<RATE>689.84</RATE>
<RESULT>Y</RESULT>
</PRICE>
<PRICE>
<RATEID>1</RATEID>
<SERVICE>15N</SERVICE>
<SERVICEDESC>Express</SERVICEDESC>
<OPTION>NONE</OPTION>
<OPTIONDESC>NONE</OPTIONDESC>
<CURRENCY>PLN</CURRENCY>
<RATE>670.03</RATE>
<RESULT>Y</RESULT>
</PRICE>
</document>
And finally deserialization code:
File.WriteAllText("priceResponse.xml", x);
//Console.WriteLine(x);
var ser = new XmlSerializer(typeof(document),new XmlRootAttribute("documentPRICE"));
using (var reader = XmlReader.Create("priceResponse.xml"))
{
var wrapper = (document)ser.Deserialize(reader);
foreach (documentPRICE item in wrapper.Items)
{
Console.WriteLine(item.OPTIONDESC);
}
}
I would like to get each items in PRICE element, but I can't deserialize xml. What am I doing wrong ?
In this line of code,
var ser = new XmlSerializer(typeof(document),new XmlRootAttribute("documentPRICE"));
you have serialized the document object but are keeping the root of the xml as documentPRICE. And here,
var wrapper = (document)ser.Deserialize(reader);
you are trying to deserialize it to document object which does not make sense.
The xml created after serializing in your case has documentPRICE as the root object but you are trying to deserialize the same to document object, which is wrong. What you need to do is to keep document as the root while serializing ,as below.
var ser = new XmlSerializer(typeof(document), new XmlRootAttribute("document"));
And it should work.
I have converted some xml into classes using xsd and now I am having an issue getting some data into the array that exists in the class to add a list of items. I am trying to get the info into OrderItemsItem.
A bit stumped, any help appreciated (not really keen on making any changes to the classes if I can get away with it, convert to List<> etc) .
This is the code to add the info:
OrderItemsItem orderItemsItem = new OrderItemsItem();
orderItemsItem.CostCentre = "sfsdf";
orderItemsItem.DeliveryDate = "2014-01-05";
orderItemsItem.Fund = "G";
orderItemsItem.ExternalLineRef = "1";
orderItemsItem.ItemName = "dfss";
orderItemsItem.LineNo = "1";
orderItemsItem.ProdId = "dfsf";
orderItemsItem.Project = "";
orderItemsItem.QuantityOrdered = "2";
orderItemsItem.UnitCost = "10";
Order order = new Order();
OrderItemsItem [] items = {orderItemsItem};
order.Items.Item = items;
The Error I am receiving is happening on -> order.Items.Item = items;:
System.NullReferenceException: Object reference not set to an instance
of an object.
This is the Class:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="XXXXXXXXX")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="XXXXXXXXX", IsNullable=false)]
public partial class Order {
private string referenceField;
private string notesField;
private string orderDateField;
private string statusField;
private OrderItems itemsField;
private OrderBuyerDetails buyerDetailsField;
/// <remarks/>
public string Reference {
get {
return this.referenceField;
}
set {
this.referenceField = value;
}
}
/// <remarks/>
public string Notes {
get {
return this.notesField;
}
set {
this.notesField = value;
}
}
/// <remarks/>
public string OrderDate {
get {
return this.orderDateField;
}
set {
this.orderDateField = value;
}
}
/// <remarks/>
public string Status {
get {
return this.statusField;
}
set {
this.statusField = value;
}
}
/// <remarks/>
public OrderItems Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
/// <remarks/>
public OrderBuyerDetails BuyerDetails {
get {
return this.buyerDetailsField;
}
set {
this.buyerDetailsField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="XXXXXXXXX")]
public partial class OrderItems {
private OrderItemsItem[] itemField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Item")]
public OrderItemsItem[] Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="XXXXXXXXX")]
public partial class OrderItemsItem {
private string lineNoField;
private string externalLineRefField;
private string prodIdField;
private string itemNameField;
private string quantityOrderedField;
private string unitCostField;
private string deliveryDateField;
private string costCentreField;
private string projectField;
private string fundField;
/// <remarks/>
public string LineNo {
get {
return this.lineNoField;
}
set {
this.lineNoField = value;
}
}
/// <remarks/>
public string ExternalLineRef {
get {
return this.externalLineRefField;
}
set {
this.externalLineRefField = value;
}
}
/// <remarks/>
public string ProdId {
get {
return this.prodIdField;
}
set {
this.prodIdField = value;
}
}
/// <remarks/>
public string ItemName {
get {
return this.itemNameField;
}
set {
this.itemNameField = value;
}
}
/// <remarks/>
public string QuantityOrdered {
get {
return this.quantityOrderedField;
}
set {
this.quantityOrderedField = value;
}
}
/// <remarks/>
public string UnitCost {
get {
return this.unitCostField;
}
set {
this.unitCostField = value;
}
}
/// <remarks/>
public string DeliveryDate {
get {
return this.deliveryDateField;
}
set {
this.deliveryDateField = value;
}
}
/// <remarks/>
public string CostCentre {
get {
return this.costCentreField;
}
set {
this.costCentreField = value;
}
}
/// <remarks/>
public string Project {
get {
return this.projectField;
}
set {
this.projectField = value;
}
}
/// <remarks/>
public string Fund {
get {
return this.fundField;
}
set {
this.fundField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="XXXXXXXXX")]
public partial class OrderBuyerDetails {
private string nameField;
private string emailField;
private OrderBuyerDetailsBillingAddress billingAddressField;
/// <remarks/>
public string Name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
public string Email {
get {
return this.emailField;
}
set {
this.emailField = value;
}
}
/// <remarks/>
public OrderBuyerDetailsBillingAddress BillingAddress {
get {
return this.billingAddressField;
}
set {
this.billingAddressField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="XXXXXXXXX")]
public partial class OrderBuyerDetailsBillingAddress {
private string nameField;
private string address1Field;
private string address2Field;
private string address3Field;
private string placeField;
private string countyField;
private string postCodeField;
private string countryField;
private string emailField;
/// <remarks/>
public string Name {
get {
return this.nameField;
}
set {
this.nameField = value;
}
}
/// <remarks/>
public string Address1 {
get {
return this.address1Field;
}
set {
this.address1Field = value;
}
}
/// <remarks/>
public string Address2 {
get {
return this.address2Field;
}
set {
this.address2Field = value;
}
}
/// <remarks/>
public string Address3 {
get {
return this.address3Field;
}
set {
this.address3Field = value;
}
}
/// <remarks/>
public string Place {
get {
return this.placeField;
}
set {
this.placeField = value;
}
}
/// <remarks/>
public string County {
get {
return this.countyField;
}
set {
this.countyField = value;
}
}
/// <remarks/>
public string PostCode {
get {
return this.postCodeField;
}
set {
this.postCodeField = value;
}
}
/// <remarks/>
public string Country {
get {
return this.countryField;
}
set {
this.countryField = value;
}
}
/// <remarks/>
public string Email {
get {
return this.emailField;
}
set {
this.emailField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="XXXXXXXXX")]
[System.Xml.Serialization.XmlRootAttribute(Namespace="XXXXXXXXX", IsNullable=false)]
public partial class Post_Printondemand_Create_Full_Order_DataSet {
private Order[] itemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Order")]
public Order[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
Thank you
order.Items.Item = items
The error must be that some order among your orders have its Items collection null (and thus making it not possible to access its "Item" property).
My suspicion is that in your example order.Items is null - you will need to attach a debugger and examine the variables yourself to determine the root cause of your null ref. Ensure that the array is not null before working with it.
in your example you're overriding an element of an array. This will either replace the existing element (if it exists) or (I believe) throw an IndexOutOfBoundsException if it doesn't.
Arrays are generally for fixed lengths of data, ones which you don't append/remove data from frequently. Lists are a better collection to use as they have Add() and Remove() functions for specifically this reason.
It is possible to "append" to C# arrays
order.Items = Order.Items.Union(new Item[]{myNewItem}));
However it's not very nice and creates a new array by merging the old ones! My advice... make the collection a list!