I have created a Structure class with the "XSD.exe" and now I have a short problem:
I have 5 different "Classes" in the Structure and all 5 Classes have the same values like this:
public partial class Carrier
{
private string codeField;
private string companyField;
private string legalNameField;
private string addressField;
private string address2Field;
private string stateField;
private string cityField;
private string countryField;
private string phoneField;
private string faxField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Code
{
get
{
return this.codeField;
}
set
{
this.codeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Company
{
get
{
return this.companyField;
}
set
{
this.companyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string LegalName
{
get
{
return this.legalNameField;
}
set
{
this.legalNameField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Address
{
get
{
return this.addressField;
}
set
{
this.addressField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Address2
{
get
{
return this.address2Field;
}
set
{
this.address2Field = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string State
{
get
{
return this.stateField;
}
set
{
this.stateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string City
{
get
{
return this.cityField;
}
set
{
this.cityField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Country
{
get
{
return this.countryField;
}
set
{
this.countryField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Phone
{
get
{
return this.phoneField;
}
set
{
this.phoneField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
public string Fax
{
get
{
return this.faxField;
}
set
{
this.faxField = value;
}
}
}
I want set all five different object to another object like this:
private Adress FindAddresses(Carrier address)
{
tempAddress = new Address();
tempAddress.AddressCode = address.Code;
tempAddress.Name1 = address.LegalName;
tempAddress.Name2 = address.Address;
tempAddress.Name3 = address.Address2;
return tempAddress;
}
Is the only way to do this to overload this function 5 times or gives an "better" way to do this ?
You could let the classes implement the same interface, for example IAdressable:
public interface IAddressable
{
public AddressCode Code { get; set; }
public string LegalName { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
}
Now the method could take an IAddressable as argument:
private Adress FindAddresses(IAddressable address)
{
var tempAddress = new Address();
tempAddress.AddressCode = address.Code;
tempAddress.Name1 = address.LegalName;
tempAddress.Name2 = address.Address;
tempAddress.Name3 = address.Address2;
return tempAddress;
}
Then you can call this method with all your classes since they all implement that interface.
You could try to move the common properties into a common base class and derive Carrier and the 4 other classes from that base class.
The methods would then take an instance of the base class.
public class BaseAddressClass
{
...
}
public class Carrier : BaseAddressClass
{
// Other fields
}
private Address FindAddress(BaseAddressClass address)
{
...
}
Related
I'm connecting to the clothing distributor SanMar using their wsdl endpoint. I've created a service reference for it but where I'm hitting a roadblock is in a specific method I want to call. It requires two params, the one that's giving me issues is an item[]. The wsdl documentation has it's own definition of an item[] which I can't seem to satisfy.
The endpoint is https://ws.sanmar.com:8080/SanMarWebServices/SanMarNotificationServicePort?WSDL
The documentation for the item[] object is:
public partial class item : object, System.ComponentModel.INotifyPropertyChanged {
private double casePriceField;
private bool casePriceFieldSpecified;
private string colorField;
private double dozenPriceField;
private bool dozenPriceFieldSpecified;
private string inventoryKeyField;
private double myPriceField;
private bool myPriceFieldSpecified;
private double piecePriceField;
private bool piecePriceFieldSpecified;
private double salePriceField;
private bool salePriceFieldSpecified;
private string sizeField;
private int sizeIndexField;
private bool sizeIndexFieldSpecified;
private string styleField;
private string saleStartDateField;
private string saleEndDateField;
private double incentivePriceField;
private bool incentivePriceFieldSpecified;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=0)]
public double casePrice {
get {
return this.casePriceField;
}
set {
this.casePriceField = value;
this.RaisePropertyChanged("casePrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool casePriceSpecified {
get {
return this.casePriceFieldSpecified;
}
set {
this.casePriceFieldSpecified = value;
this.RaisePropertyChanged("casePriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)]
public string color {
get {
return this.colorField;
}
set {
this.colorField = value;
this.RaisePropertyChanged("color");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=2)]
public double dozenPrice {
get {
return this.dozenPriceField;
}
set {
this.dozenPriceField = value;
this.RaisePropertyChanged("dozenPrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool dozenPriceSpecified {
get {
return this.dozenPriceFieldSpecified;
}
set {
this.dozenPriceFieldSpecified = value;
this.RaisePropertyChanged("dozenPriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=3)]
public string inventoryKey {
get {
return this.inventoryKeyField;
}
set {
this.inventoryKeyField = value;
this.RaisePropertyChanged("inventoryKey");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=4)]
public double myPrice {
get {
return this.myPriceField;
}
set {
this.myPriceField = value;
this.RaisePropertyChanged("myPrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool myPriceSpecified {
get {
return this.myPriceFieldSpecified;
}
set {
this.myPriceFieldSpecified = value;
this.RaisePropertyChanged("myPriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=5)]
public double piecePrice {
get {
return this.piecePriceField;
}
set {
this.piecePriceField = value;
this.RaisePropertyChanged("piecePrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool piecePriceSpecified {
get {
return this.piecePriceFieldSpecified;
}
set {
this.piecePriceFieldSpecified = value;
this.RaisePropertyChanged("piecePriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=6)]
public double salePrice {
get {
return this.salePriceField;
}
set {
this.salePriceField = value;
this.RaisePropertyChanged("salePrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool salePriceSpecified {
get {
return this.salePriceFieldSpecified;
}
set {
this.salePriceFieldSpecified = value;
this.RaisePropertyChanged("salePriceSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=7)]
public string size {
get {
return this.sizeField;
}
set {
this.sizeField = value;
this.RaisePropertyChanged("size");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=8)]
public int sizeIndex {
get {
return this.sizeIndexField;
}
set {
this.sizeIndexField = value;
this.RaisePropertyChanged("sizeIndex");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool sizeIndexSpecified {
get {
return this.sizeIndexFieldSpecified;
}
set {
this.sizeIndexFieldSpecified = value;
this.RaisePropertyChanged("sizeIndexSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=9)]
public string style {
get {
return this.styleField;
}
set {
this.styleField = value;
this.RaisePropertyChanged("style");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=10)]
public string saleStartDate {
get {
return this.saleStartDateField;
}
set {
this.saleStartDateField = value;
this.RaisePropertyChanged("saleStartDate");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=11)]
public string saleEndDate {
get {
return this.saleEndDateField;
}
set {
this.saleEndDateField = value;
this.RaisePropertyChanged("saleEndDate");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=12)]
public double incentivePrice {
get {
return this.incentivePriceField;
}
set {
this.incentivePriceField = value;
this.RaisePropertyChanged("incentivePrice");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool incentivePriceSpecified {
get {
return this.incentivePriceFieldSpecified;
}
set {
this.incentivePriceFieldSpecified = value;
this.RaisePropertyChanged("incentivePriceSpecified");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
Can anyone point me in the right direction or pm me to talk further?
Thank you
I tried creating an item[] from scratch but I believe I'm supposed to be using the methods to set the values.
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;
}
}
}
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
Below is the portion of code from Propertyware API that is consumed.
public OwnerLedger appendOwnerLedgerItems(OwnerLedger ownerLedger, Owner owner) {
object[] results = this.Invoke("appendOwnerLedgerItems", new object[] {
ownerLedger,
owner});
return ((OwnerLedger)(results[0]));
}
public partial class OwnerLedger : Ledger {
}
public abstract partial class Ledger : ClientDataContainer {
private LedgerItem[] itemsField;
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public LedgerItem[] items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
public abstract partial class LedgerItem : FinancialTransaction {
}
public abstract partial class OwnerLedgerItem : LedgerItem {
}
public partial class OwnerContribution : OwnerLedgerItem {
private string commentsField;
private System.Nullable<System.DateTime> dateField;
private string paymentTypeField;
private string referenceNumberField;
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string comments {
get {
return this.commentsField;
}
set {
this.commentsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public System.Nullable<System.DateTime> date {
get {
return this.dateField;
}
set {
this.dateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string paymentType {
get {
return this.paymentTypeField;
}
set {
this.paymentTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string referenceNumber {
get {
return this.referenceNumberField;
}
set {
this.referenceNumberField = value;
}
}
}
In the above code i need to use the "appendOwnerLedgerItems" method to create an owner contribution entry in Propertyware. For that i try to use the below logic but it fails. The error message is "java.lang.ClassCastException: [Lcom.realpage.propertyware.web.service.soap.AbstractLedgerItemDTO; cannot be cast to [Lcom.realpage.propertyware.web.service.soap.AbstractOwnerLedgerItemDTO;"
OwnerContribution oc = new OwnerContribution();
oc.amount = 10;
oc.comments = "Test Entry";
oc.date = System.DateTime.Now;
oc.paymentType = "Check";
oc.referenceNumber = "12345";
Owner ow = new Owner();
ow.ID = 12345;
LedgerItem[] li = new LedgerItem[1];
li[0] = oc;
OwnerLedger owl = new OwnerLedger();
owl.items = li;
OwnerLedger owl1 = client.appendOwnerLedgerItems(owl,ow); // This is where i get the cast error
How to solve this issue?
I don't know much about Propertyware but can you try this, basically change the order of objects passed to the invoke method:
public OwnerLedger appendOwnerLedgerItems(OwnerLedger ownerLedger, Owner owner) {
object[] results = this.Invoke("appendOwnerLedgerItems", new object[] {
owner, ownerLedger});
return ((OwnerLedger)(results[0]));
}
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>