How to load XML data to a data structure? - c#

I have the following XML document
<?xml version = "1.0" encoding = "utf-8"?>
<flights_for_sale>
<ad id="0001" createdon ="11/02/20" expireson="12/02/20">
<aircraft id="A10">
<year> 1977 </year>
<make> <![CDATA[&c;]]> </make>
<model> Skyhawk </model>
<color> Light blue and white </color>
<description>
New paint, nearly new interior,
685 hours SMOH, full IFR King avionics
</description>
<price> 23,495 </price>
</aircraft>
<seller id = "s001" phone="123-123-123"> Skyway Aircraft </seller>
<seller id = "s002" phone="123-123-222"> Boeing </seller>
<seller id = "s003" phone="123-123-233"> McDouglas </seller>
<membership id="1000" from="12/03/16" to="12/03/18" no="M0001">Silver</membership>
<membership id="1000" from="12/03/16" to="12/03/18" no="M0002">Gold</membership>
<membership id="1000" from="12/03/16" to="12/03/18" no="M0003">Platinum</membership>
<location>
<city> Rapid City, </city>
<state> South Dakota </state>
</location>
</ad>
<ad id="002" createdon ="11/05/20" expireson="12/05/20">
<aircraft>
<year> 1965 </year>
<make> &p; </make>
<model> Cherokee </model>
<color> Gold </color>
<description>
240 hours SMOH, dual NAVCOMs, DME,
new Cleveland brakes, great shape
</description>
</aircraft>
<seller phone="555-333-2222" email="jseller#www.axl.com" id="s004">John Seller</seller>
<membership id="1000" from="12/03/16" to="12/03/18" no="M0020">State Membership</membership>
<membership id="1000" from="12/03/16" to="12/03/18" no="M0002">Gold</membership>
<location>
<city> St. Joseph, </city>
<state> Missouri </state>
</location>
</ad>
</flights_for_sale>
I have the following C# classes
class Advert2
{
public int? Id { get; set; }
public DateTime? CreatedOn { get; set; }
public DateTime? ExpiresOn { get; set; }
public Aircraft MyAircraft { get; set; }
public List<Seller2> MySellers { get; set; }
public List<Membership> MyMemberships { get; set; }
public Advert2()
{
MySellers = new List<Seller2>();
MyMemberships = new List<Membership>();
MyAircraft = new Aircraft();
}
}
class Seller2
{
public int? Id { get; set; }
public string SellerName { get; set; }
public string Phone { get; set; }
}
class Membership
{
public int? Id { get; set; }
public string MembershipNumber { get; set; }
public DateTime? From { get; set; }
public DateTime? To { get; set; }
public String MemberType { get; set; }
}
class Aircraft {
public string Make { get; set; }
public string Model { get; set; }
public decimal? Price { get; set; }
public string Description { get; set; }
}
Then i have used the following two methods to parse XML elements and attributes ( check for NULLs )
public static class XMLCommons
{
public static string TryGetElementValue(this XElement parentEl, string elementName, string defaultValue = null)
{
var foundEl = parentEl.Element(elementName);
if (foundEl != null)
{
return foundEl.Value;
}
return defaultValue;
}
public static string TryGetAttribtueValue(this XElement parentEl, string elementName, string attrName, string defaultValue = null)
{
var foundEl = parentEl.Element(elementName);
if (foundEl != null) {
//check attribute exists
var foundAttr = foundEl.Attribute(attrName);
if (foundAttr != null)
{
return foundAttr.Value;
}
}
return defaultValue;
}
}
Then i have written the following code to read element/attributes on the XML, and populate data to the Advert2 object structure
var xmlPath2 = System.IO.Path.Combine("../../../data/" + "XMLFile2.xml");
var xml2 = XDocument.Load(xmlPath2);
var query2 = xml2.Root.Descendants("ad").Select(n => new Advert2 {
Id = Convert.ToInt32(n.Parent.TryGetAttribtueValue("ad", "id")),
CreatedOn = Convert.ToDateTime( n.Parent.TryGetAttribtueValue("ad", "createdon") ),
ExpiresOn = Convert.ToDateTime(n.Parent.TryGetAttribtueValue("ad", "expireson")),
MyAircraft = new Aircraft {
Make = n.TryGetElementValue("make"),
Model = n.TryGetElementValue("model"),
Description = n.TryGetElementValue("description"),
Price = Convert.ToDecimal( n.TryGetElementValue("price") ) },
MySellers = new List<Seller2>().Add( new Seller2 {
Id = Convert.ToInt32( n.TryGetAttribtueValue("seller","id") ),
SellerName = n.TryGetElementValue("seller"),
Phone = n.TryGetAttribtueValue("seller","phone")
} )
}).ToList();
but the issues is i get syntax errors when i tried to create objects to populate MySellers List.
Error:
Error CS0029
Cannot implicitly convert type 'void' to System.Collections.Generic.List<XMLParsing.Seller2>'
So it seems like i don't know how to populate those two collections MySellers and MyMemberships.
is there away to populate those two collections so i can create the Averts2 Collection?

I know this is not quite in the spirit of the question. However, it should be as simple as
var xmlStream = new StreamReader(#"D:\something.xml");
var serializer = new XmlSerializer(typeof(flights_for_sale));
var result = (flights_for_sale)serializer.Deserialize(xmlStream);
The below was obtained by pasting the xml into visual studio
Edit 🡆 Paste Special 🡆 Paste XML as Classes
// 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)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class flights_for_sale
{
private flights_for_saleAD[] adField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("ad")]
public flights_for_saleAD[] ad
{
get
{
return this.adField;
}
set
{
this.adField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleAD
{
private flights_for_saleADAircraft aircraftField;
private flights_for_saleADSeller[] sellerField;
private flights_for_saleADMembership[] membershipField;
private flights_for_saleADLocation locationField;
private byte idField;
private string createdonField;
private string expiresonField;
/// <remarks/>
public flights_for_saleADAircraft aircraft
{
get
{
return this.aircraftField;
}
set
{
this.aircraftField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("seller")]
public flights_for_saleADSeller[] seller
{
get
{
return this.sellerField;
}
set
{
this.sellerField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("membership")]
public flights_for_saleADMembership[] membership
{
get
{
return this.membershipField;
}
set
{
this.membershipField = value;
}
}
/// <remarks/>
public flights_for_saleADLocation location
{
get
{
return this.locationField;
}
set
{
this.locationField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public byte id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string createdon
{
get
{
return this.createdonField;
}
set
{
this.createdonField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string expireson
{
get
{
return this.expiresonField;
}
set
{
this.expiresonField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleADAircraft
{
private ushort yearField;
private string makeField;
private string modelField;
private string colorField;
private string descriptionField;
private string priceField;
private string idField;
/// <remarks/>
public ushort year
{
get
{
return this.yearField;
}
set
{
this.yearField = value;
}
}
/// <remarks/>
public string make
{
get
{
return this.makeField;
}
set
{
this.makeField = value;
}
}
/// <remarks/>
public string model
{
get
{
return this.modelField;
}
set
{
this.modelField = value;
}
}
/// <remarks/>
public string color
{
get
{
return this.colorField;
}
set
{
this.colorField = value;
}
}
/// <remarks/>
public string description
{
get
{
return this.descriptionField;
}
set
{
this.descriptionField = value;
}
}
/// <remarks/>
public string price
{
get
{
return this.priceField;
}
set
{
this.priceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleADSeller
{
private string idField;
private string phoneField;
private string emailField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string phone
{
get
{
return this.phoneField;
}
set
{
this.phoneField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string email
{
get
{
return this.emailField;
}
set
{
this.emailField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleADMembership
{
private ushort idField;
private string fromField;
private string toField;
private string noField;
private string valueField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public ushort id
{
get
{
return this.idField;
}
set
{
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string from
{
get
{
return this.fromField;
}
set
{
this.fromField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string to
{
get
{
return this.toField;
}
set
{
this.toField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string no
{
get
{
return this.noField;
}
set
{
this.noField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTextAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class flights_for_saleADLocation
{
private string cityField;
private string stateField;
/// <remarks/>
public string city
{
get
{
return this.cityField;
}
set
{
this.cityField = value;
}
}
/// <remarks/>
public string state
{
get
{
return this.stateField;
}
set
{
this.stateField = value;
}
}
}

Related

How can we pass XML as request to .Net core API and get response in XML from Same API in c#?

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

Manually populate object generated fom xsd in C#

Sorry, new to all this...
I have an XSD file which I used to create classes in C# using XSD.exe.
The challenge now is trying to figure out how to manually populate the object so I can then serialise to XML (I won't have a source XML file so I need to manually set the properties via an alternate source).
Below is a sample classes generated from the XSD file. I'm able to set the filesummary and debtor information but no idea how to set the debtorcontact information.
<?xml version="1.0" encoding="utf-8"?>
<FileSummary FileDate="1900-01-01T01:01:01+08:00" OpeningBalance="1" Invoices="1" DebitNotes="1" CreditNotes="1" CashReceipts="1" OtherPositive="1" OtherNegative="1" ClosingBalance="1">
<Debtor DebtorId="DebtorId2" DebtorName="DebtorName2" ExcludedDebtor="ExcludedDebtor2" CreditLimit="-79228162514264337593543950335" DebtorStatus="DebtorStatus2" TradingTerms="TradingTerms2" OverduePeriod="4294967295" HeadOfficeCode="HeadOfficeCode2" HeadOfficeName="HeadOfficeName2" DebtorCountry="DebtorCountry2" ABN="ABN2" ARBN="ARBN2" ACN="ACN2" LegalName="LegalName2" MainTradingName="MainTradingName2" OtherTradingName="OtherTradingName2">
<DebtorContact Surname="Surname4" FirstName="FirstName4" OtherNames="OtherNames4" Phone="Phone4" Mobile="Mobile4" Fax="Fax4" Email="Email4" Salutation="Salutation4" JobTitle="JobTitle4" ContactAddress="ContactAddress4" ContactSuburb="ContactSuburb4" ContactCountry="ContactCountry4" ContactState="ContactState4" ContactPostcode="ContactPostcode4" />
<DebtorContact Surname="Surname5" FirstName="FirstName5" OtherNames="OtherNames5" Phone="Phone5" Mobile="Mobile5" Fax="Fax5" Email="Email5" Salutation="Salutation5" JobTitle="JobTitle5" ContactAddress="ContactAddress5" ContactSuburb="ContactSuburb5" ContactCountry="ContactCountry5" ContactState="ContactState5" ContactPostcode="ContactPostcode5" />
</Debtor>
</FileSummary>
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// 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.6.1055.0.
//
/// <remarks/>
[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 FileSummary {
private FileSummaryDebtor[] debtorField;
private System.DateTime fileDateField;
private decimal openingBalanceField;
private decimal invoicesField;
private decimal debitNotesField;
private decimal creditNotesField;
private decimal cashReceiptsField;
private decimal otherPositiveField;
private decimal otherNegativeField;
private decimal closingBalanceField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Debtor")]
public FileSummaryDebtor[] Debtor {
get {
return this.debtorField;
}
set {
this.debtorField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public System.DateTime FileDate {
get {
return this.fileDateField;
}
set {
this.fileDateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal OpeningBalance {
get {
return this.openingBalanceField;
}
set {
this.openingBalanceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal Invoices {
get {
return this.invoicesField;
}
set {
this.invoicesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal DebitNotes {
get {
return this.debitNotesField;
}
set {
this.debitNotesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal CreditNotes {
get {
return this.creditNotesField;
}
set {
this.creditNotesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal CashReceipts {
get {
return this.cashReceiptsField;
}
set {
this.cashReceiptsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal OtherPositive {
get {
return this.otherPositiveField;
}
set {
this.otherPositiveField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal OtherNegative {
get {
return this.otherNegativeField;
}
set {
this.otherNegativeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal ClosingBalance {
get {
return this.closingBalanceField;
}
set {
this.closingBalanceField = value;
}
}
}
/// <remarks/>
[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 FileSummaryDebtor {
private object[] itemsField;
private string debtorIdField;
private string debtorNameField;
private string excludedDebtorField;
private decimal creditLimitField;
private string debtorStatusField;
private string tradingTermsField;
private uint overduePeriodField;
private string headOfficeCodeField;
private string headOfficeNameField;
private string debtorCountryField;
private string aBNField;
private string aRBNField;
private string aCNField;
private string legalNameField;
private string mainTradingNameField;
private string otherTradingNameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("DebtorContact", typeof(FileSummaryDebtorDebtorContact))]
public object[] Items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DebtorId {
get {
return this.debtorIdField;
}
set {
this.debtorIdField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DebtorName {
get {
return this.debtorNameField;
}
set {
this.debtorNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ExcludedDebtor {
get {
return this.excludedDebtorField;
}
set {
this.excludedDebtorField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal CreditLimit {
get {
return this.creditLimitField;
}
set {
this.creditLimitField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DebtorStatus {
get {
return this.debtorStatusField;
}
set {
this.debtorStatusField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string TradingTerms {
get {
return this.tradingTermsField;
}
set {
this.tradingTermsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public uint OverduePeriod {
get {
return this.overduePeriodField;
}
set {
this.overduePeriodField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string HeadOfficeCode {
get {
return this.headOfficeCodeField;
}
set {
this.headOfficeCodeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string HeadOfficeName {
get {
return this.headOfficeNameField;
}
set {
this.headOfficeNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string DebtorCountry {
get {
return this.debtorCountryField;
}
set {
this.debtorCountryField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ABN {
get {
return this.aBNField;
}
set {
this.aBNField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ARBN {
get {
return this.aRBNField;
}
set {
this.aRBNField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ACN {
get {
return this.aCNField;
}
set {
this.aCNField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string LegalName {
get {
return this.legalNameField;
}
set {
this.legalNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string MainTradingName {
get {
return this.mainTradingNameField;
}
set {
this.mainTradingNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string OtherTradingName {
get {
return this.otherTradingNameField;
}
set {
this.otherTradingNameField = value;
}
}
}
/// <remarks/>
[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 FileSummaryDebtorDebtorContact {
private string surnameField;
private string firstNameField;
private string otherNamesField;
private string phoneField;
private string mobileField;
private string faxField;
private string emailField;
private string salutationField;
private string jobTitleField;
private string contactAddressField;
private string contactSuburbField;
private string contactCountryField;
private string contactStateField;
private string contactPostcodeField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Surname {
get {
return this.surnameField;
}
set {
this.surnameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string FirstName {
get {
return this.firstNameField;
}
set {
this.firstNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string OtherNames {
get {
return this.otherNamesField;
}
set {
this.otherNamesField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Phone {
get {
return this.phoneField;
}
set {
this.phoneField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Mobile {
get {
return this.mobileField;
}
set {
this.mobileField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Fax {
get {
return this.faxField;
}
set {
this.faxField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Email {
get {
return this.emailField;
}
set {
this.emailField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string Salutation {
get {
return this.salutationField;
}
set {
this.salutationField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string JobTitle {
get {
return this.jobTitleField;
}
set {
this.jobTitleField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ContactAddress {
get {
return this.contactAddressField;
}
set {
this.contactAddressField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ContactSuburb {
get {
return this.contactSuburbField;
}
set {
this.contactSuburbField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ContactCountry {
get {
return this.contactCountryField;
}
set {
this.contactCountryField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ContactState {
get {
return this.contactStateField;
}
set {
this.contactStateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public string ContactPostcode {
get {
return this.contactPostcodeField;
}
set {
this.contactPostcodeField = value;
}
}
}
using System;
namespace CoinsAssetWatchXMLGen
{
class Program
{
static void Main(string[] args)
{
FileSummary fileSummary = new FileSummary();
fileSummary.FileDate = DateTime.Today;
FileSummaryDebtor debtor = new FileSummaryDebtor;
debtor.DebtorId = "11";
debtor.DebtorName = "fred";
debtor.DebtorStatus = "active";
debtor.ABN = "ABC1234567";
fileSummary.Debtor[1] = debtor;
//how do I associate this following with a debtor for XML??
FileSummaryDebtorDebtorContact contact = new FileSummaryDebtorDebtorContact();
}
}
}
The approach I took was to create a dataset classes using xsd.exe /d.
Once the data set classes were created
I initially populated the data table as follows just to get a better understanding of the data set structure:
NewDataSet newDataSet = new NewDataSet();
newDataSet.ReadXml("FileSummary.xml");

XML Deserialization is not working

I'm trying to deserialize the below XML but the process seems not to be working...
Here's what I get when I display the values in a PropertyGrid control after deserializing the XML:
As you can see, the elements under Header has no values.
Can you please help to check what's wrong with the codes?
Message class:
namespace MyProject
{
[XmlRoot(ElementName="Header")]
public class Header {
[XmlElement(ElementName="Sender")]
public string Sender { get; set; }
[XmlElement(ElementName="Receiver")]
public string Receiver { get; set; }
[XmlElement(ElementName="MessageID")]
public string MessageID { get; set; }
[XmlElement(ElementName="CreationDateTime")]
public string CreationDateTime { get; set; }
[XmlAttribute(AttributeName="version")]
public string Version { get; set; }
}
[XmlRoot(ElementName="Message", Namespace="http://example.com")]
public class Message {
private Header _header = new Header();
[XmlElement(ElementName="Header")]
[TypeConverter(typeof(ConverterExpandableObject))]
public Header Header
{
get { return _header; }
set { _header = value; }
}
[XmlAttribute(AttributeName="ns", Namespace="http://www.w3.org/2000/xmlns/")]
public string Ns { get; set; }
}
}
Method to deserialize the XML:
void DeserializeMessage()
{
string messageString = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Message.xml";
if (File.Exists(messageString))
{
XmlSerializer serializer = new XmlSerializer(typeof(Message));
StreamReader reader = new StreamReader(messageString);
Message m = (Message)serializer.Deserialize(reader);
reader.Close();
propertyGrid1.SelectedObject = m;
}
}
and the XML itself:
<?xml version="1.0" encoding="UTF-8"?>
<ns:Message xmlns:ns="http://example.com">
<Header version="1.0">
<Sender>3015207400109</Sender>
<Receiver>8711200999903</Receiver>
<MessageID>000D2613F64AC021ED783C084735EC78E53</MessageID>
<CreationDateTime>2017-03-21T08:00:47Z</CreationDateTime>
</Header>
</ns:Message>
change you classes like below and it will work.
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://example.com")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://example.com", IsNullable = false)]
public partial class Message
{
private Header headerField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Namespace = "")]
public Header Header
{
get
{
return this.headerField;
}
set
{
this.headerField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class Header
{
private ulong senderField;
private ulong receiverField;
private string messageIDField;
private System.DateTime creationDateTimeField;
private decimal versionField;
/// <remarks/>
public ulong Sender
{
get
{
return this.senderField;
}
set
{
this.senderField = value;
}
}
/// <remarks/>
public ulong Receiver
{
get
{
return this.receiverField;
}
set
{
this.receiverField = value;
}
}
/// <remarks/>
public string MessageID
{
get
{
return this.messageIDField;
}
set
{
this.messageIDField = value;
}
}
/// <remarks/>
public System.DateTime CreationDateTime
{
get
{
return this.creationDateTimeField;
}
set
{
this.creationDateTimeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute()]
public decimal version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
}
}
}
OUTPUT

Complex XML deserialization

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

Programmatically controlling the order of xml elements

I'm using a third part web service[WS] in my .Net app.
My application is using the entity classes generated from this WS's wsdl.
I fetch the data from db, fill it in entity objects and then generate an xml out of it using XmlSerializer class.
One of the methods of the WS requires this xml string as input.And the xml should have elements in the same order as expected by the WS.But whats happening is that some of the elements are getting upside down in my app and so WS is throwing an innermost exception saying on serialzation:.
_innerException {"Inconsistent sequencing: if used on one of the class's members, the 'Order' property is required on all particle-like members, please explicitly set 'Order' using XmlElement, XmlAnyElement or XmlArray custom attribute on class member 'instrument'."} System.Exception {System.InvalidOperationException}
XmlSerializer serializer = new XmlSerializer(typeof(totemmessage));
So,my question here is, how do I programmatically control the order of these xml elements in my app before sending it to the WS?Note:I dont want to use xslt for this purpose.
Thanks for reading.
Here are my entity classes:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="totem-message")]
[System.Xml.Serialization.XmlRootAttribute("totem", Namespace="", IsNullable=false)]
public partial class totemmessage {
private object itemField;
private ItemChoiceType1 itemElementNameField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("error", typeof(errorinfo))]
[System.Xml.Serialization.XmlElementAttribute("parseReport", typeof(parseReportinfo))]
[System.Xml.Serialization.XmlElementAttribute("results", typeof(templateinfo))]
[System.Xml.Serialization.XmlElementAttribute("subareas", typeof(subareasinfo))]
[System.Xml.Serialization.XmlElementAttribute("template", typeof(templateinfo))]
[System.Xml.Serialization.XmlElementAttribute("upload", typeof(templateinfo))]
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
[System.Xml.Serialization.XmlElement(Order = 0)]
public object Item {
get {
return this.itemField;
}
set {
this.itemField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 1)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemChoiceType1 ItemElementName {
get {
return this.itemElementNameField;
}
set {
this.itemElementNameField = value;
}
}
}
[System.Xml.Serialization.XmlIncludeAttribute(typeof(energyInstrument))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
public abstract partial class abstractEnergyInstrument {
private energyContractTime periodField;
private bool periodFieldSpecified;
private System.DateTime startDateField;
private bool startDateFieldSpecified;
private System.DateTime endDateField;
private bool endDateFieldSpecified;
private System.DateTime expiryDateField;
private bool expiryDateFieldSpecified;
private energyInstrumentClassifier typeField;
private bool typeFieldSpecified;
private string strikeField;
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 0)]
public energyContractTime period {
get {
return this.periodField;
}
set {
this.periodField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 1)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool periodSpecified {
get {
return this.periodFieldSpecified;
}
set {
this.periodFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="date", Order =2)]
public System.DateTime startDate {
get {
return this.startDateField;
}
set {
this.startDateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 3)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool startDateSpecified {
get {
return this.startDateFieldSpecified;
}
set {
this.startDateFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="date", Order =4)]
public System.DateTime endDate {
get {
return this.endDateField;
}
set {
this.endDateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 5)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool endDateSpecified {
get {
return this.endDateFieldSpecified;
}
set {
this.endDateFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="date", Order =6)]
public System.DateTime expiryDate {
get {
return this.expiryDateField;
}
set {
this.expiryDateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 7)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool expiryDateSpecified {
get {
return this.expiryDateFieldSpecified;
}
set {
this.expiryDateFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 8)]
public energyInstrumentClassifier type {
get {
return this.typeField;
}
set {
this.typeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 9)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool typeSpecified {
get {
return this.typeFieldSpecified;
}
set {
this.typeFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 10)]
public string strike {
get {
return this.strikeField;
}
set {
this.strikeField = value;
}
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlRootAttribute("instrument", Namespace="", IsNullable=false)]
public partial class energyInstrument : abstractEnergyInstrument {
private decimal priceField;
private bool priceFieldSpecified;
private decimal forwardField;
private bool forwardFieldSpecified;
private decimal volField;
private bool volFieldSpecified;
private decimal consensusPriceField;
private bool consensusPriceFieldSpecified;
private decimal compositePriceField;
private bool compositePriceFieldSpecified;
private decimal reconstitutedForwardField;
private bool reconstitutedForwardFieldSpecified;
private decimal consensusVolField;
private bool consensusVolFieldSpecified;
private decimal compositeVolField;
private bool compositeVolFieldSpecified;
private string priceOutField;
private decimal priceRangeField;
private bool priceRangeFieldSpecified;
private decimal priceStddevField;
private bool priceStddevFieldSpecified;
private string volOutField;
private decimal volRangeField;
private bool volRangeFieldSpecified;
private decimal volStddevField;
private bool volStddevFieldSpecified;
private string contributorsField;
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 0)]
public decimal price {
get {
return this.priceField;
}
set {
this.priceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 1)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool priceSpecified {
get {
return this.priceFieldSpecified;
}
set {
this.priceFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 2)]
public decimal forward {
get {
return this.forwardField;
}
set {
this.forwardField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 3)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool forwardSpecified {
get {
return this.forwardFieldSpecified;
}
set {
this.forwardFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 4)]
public decimal vol {
get {
return this.volField;
}
set {
this.volField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 5)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool volSpecified {
get {
return this.volFieldSpecified;
}
set {
this.volFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 6)]
public decimal consensusPrice {
get {
return this.consensusPriceField;
}
set {
this.consensusPriceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 7)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool consensusPriceSpecified {
get {
return this.consensusPriceFieldSpecified;
}
set {
this.consensusPriceFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 8)]
public decimal compositePrice {
get {
return this.compositePriceField;
}
set {
this.compositePriceField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 9)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool compositePriceSpecified {
get {
return this.compositePriceFieldSpecified;
}
set {
this.compositePriceFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 10)]
public decimal reconstitutedForward {
get {
return this.reconstitutedForwardField;
}
set {
this.reconstitutedForwardField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 11)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool reconstitutedForwardSpecified {
get {
return this.reconstitutedForwardFieldSpecified;
}
set {
this.reconstitutedForwardFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 12)]
public decimal consensusVol {
get {
return this.consensusVolField;
}
set {
this.consensusVolField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 13)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool consensusVolSpecified {
get {
return this.consensusVolFieldSpecified;
}
set {
this.consensusVolFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 14)]
public decimal compositeVol {
get {
return this.compositeVolField;
}
set {
this.compositeVolField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 15)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool compositeVolSpecified {
get {
return this.compositeVolFieldSpecified;
}
set {
this.compositeVolFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 16)]
public string priceOut {
get {
return this.priceOutField;
}
set {
this.priceOutField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 17)]
public decimal priceRange {
get {
return this.priceRangeField;
}
set {
this.priceRangeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 18)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool priceRangeSpecified {
get {
return this.priceRangeFieldSpecified;
}
set {
this.priceRangeFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 19)]
public decimal priceStddev
{
get {
return this.priceStddevField;
}
set {
this.priceStddevField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 20)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool priceStddevSpecified {
get {
return this.priceStddevFieldSpecified;
}
set {
this.priceStddevFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 21)]
public string volOut {
get {
return this.volOutField;
}
set {
this.volOutField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 22)]
public decimal volRange {
get {
return this.volRangeField;
}
set {
this.volRangeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 23)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool volRangeSpecified {
get {
return this.volRangeFieldSpecified;
}
set {
this.volRangeFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 24)]
public decimal volStddev {
get {
return this.volStddevField;
}
set {
this.volStddevField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElement(Order = 25)]
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool volStddevSpecified {
get {
return this.volStddevFieldSpecified;
}
set {
this.volStddevFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(DataType="integer", Order =26)]
public string contributors {
get {
return this.contributorsField;
}
set {
this.contributorsField = value;
}
}
}
I used XmlElement[Order =n] on top of each of the properties in the entity classes. So, after playing around with the ordering, I could made this serialization work.Inheritance and partial classes made this fix all the more difficult!Thanks.
The XmlSerializer generates the elements in the order of declaration in the class - can you just change the order in the entity?
How to use Order = N together with other XML attributes and List collection.
public class MyClass
{
[XmlAnyElement("My-XLMComment", Order = 3)] public XmlComment CommentA { get; set; } = new XmlDocument().CreateComment("This is an XML comment");
[XmlAttribute("MyAttribute")] public string str4 { get; set; } //This is a XML-Attribute, Order not applicable
[XmlIgnore] public string str1 { get; set; } //This is a [XmlIgnore], Order not applicable
[XmlElement(Order = 5)] public string str2 { get; set; } // Standard property with Order
[XmlElement(Order = 2)] public string str3 { get; set; } // Standard property with Order
[XmlElement(Order = 1)] public List<MyList> ListElms = new List<MyList> //List collection with Order
{
new ListElm {str1 = "xxx", str2 ="yyy", str3 ="zzz"} ,
new ListElm {str1 = "xxx", str2 ="yyy", str3 ="zzz"}
};
public class MyList
{
[XmlElement(Order = 3)] public string str1 { get; set; } // Order can be assigned, but not mandatory
[XmlElement(Order = 2)] public string str2 { get; set; } // Order can be assigned, but not mandatory
[XmlElement(Order = 1)] public string str3 { get; set; } // Order can be assigned, but not mandatory
}
}
Will serialize to:
<MyClass MyAttribute="str4">
<ListElms>
<str3>zzz</str3>
<str2>yyy</str2>
<str1>xxx</str1>
</ListElms>
<ListElms>
<str3>zzz</str3>
<str2>yyy</str2>
<str1>xxx</str1>
</ListElms>
<str3>str3</str3>
<!--This is an XML comment-->
<str2>str2</str2>
</MyClass>

Categories

Resources