Home > Software engineering >  XML Mapping is not workiing - C#
XML Mapping is not workiing - C#

Time:09-23

I am working in project for fun where, I have to deserialize my XML below:

<?xml version="1.0" encoding="utf-8"?>
<Remote Created="2022-09-13T09:45:05" Version="1.0.20.2.6.5" SerialNumber="2081" Site="Site" InstallationDate="0001-01-01T00:00:00">
  <Setup File="Qwerty" Name="Ytrewq" Encoding="Win32" Decimals="2">
    <Transaction SequenceNumber="1000609" StartTime="2022-09-13T09:42:52" EndTime="2022-09-13T09:45:05" Total="3.85" ExpectedTotal="0.00">
      <Identities>
        <Ident Name="Box" Value="1" InHierarchy="yes" />
        <Ident Name="Area" Value="1" InHierarchy="yes" />
      </Identities>
      <Charges Reject="0" Total="3.85">
        <Charge Name="Reject" Label="R" Value="0" Count="0" Total="0.00" />
        <Charge Name="10 counts" Label="" Value="10" Count="1" Total="0.10" />
        <Charge Name="20 counts" Label="" Value="20" Count="1" Total="0.20" />
        <Charge Name="50 counts" Label="" Value="50" Count="1" Total="0.50" />
        <Charge Name="1 counts" Label="" Value="100" Count="1" Total="1.00" />
        <Charge Name="2 counts" Label="" Value="200" Count="1" Total="2.00" />
        <Charge Name="5 counts" Label="" Value="5" Count="1" Total="0.05" />
      </Charges >
    </Transaction>
  </Setup>
</Remote>

And this is my object:

[XmlRoot("Remote")]
    public class Remote
    {
        //Remote
        [XmlAttribute(AttributeName = "Created")]
        public string Created { get; set; }

        [XmlAttribute(AttributeName = "Version")]
        public string Version { get; set; }

        [XmlAttribute(AttributeName = "SerialNumber")]
        public string SerialNumber { get; set; }

        [XmlAttribute(AttributeName = "Site")]
        public string Site { get; set; }

        [XmlAttribute(AttributeName = "InstallationDate")]
        public DateTime InstallationDate { get; set; }

        //Setup
        [XmlElement(ElementName = "File")]
        public string File { get; set; }

        [XmlElement(ElementName = "Name")]
        public string Name { get; set; }

        [XmlElement(ElementName = "Encoding")]
        public string Encoding { get; set; }

        [XmlElement(ElementName = "Decimals")]
        public int Decimals { get; set; }


        //Transaction
        [XmlAttribute(AttributeName = "SequenceNumber")]
        public int SequenceNumber { get; set; }

        [XmlAttribute(AttributeName = "StartTime")]
        public DateTime StartTime { get; set; }

        [XmlAttribute(AttributeName = "EndTime")]
        public DateTime EndTime { get; set; }

        [XmlAttribute(AttributeName = "Total")]
        public double Total { get; set; }

        [XmlAttribute(AttributeName = "ExpectedTotal")]
        public double ExpectedTotal { get; set; }

        [XmlArrayItem(ElementName = "Identities")]
        public List<Ident> Identities { get; set; } = new List<Ident> { };

        [XmlArrayItem(ElementName = "Charges")]
        public List<Charges> Charges{ get; set; } = new List<Charges> { };

        [XmlAttribute(AttributeName = "Reject")]
        public string Reject { get; set; }


        [XmlType("Charge")]
        public class Charges
        {
            [XmlAttribute(AttributeName = "Name")]
            public string Name { get; set; }

            [XmlAttribute(AttributeName = "Label")]
            public string Label { get; set; }

            [XmlAttribute(AttributeName = "Value")]
            public double Value { get; set; }

            [XmlAttribute(AttributeName = "Count")]
            public int Count { get; set; }

            [XmlAttribute(AttributeName = "Total")]
            public double Total { get; set; }
        }

        [XmlType("Ident")]
        public class Ident
        {
            [XmlAttribute(AttributeName = "Name")]
            public string Name { get; set; }

            [XmlAttribute(AttributeName = "Value")]
            public int Value { get; set; }

            [XmlAttribute(AttributeName = "InHierarchy")]
            public string InHierarchy { get; set; }
        }
    }

After that, I have to serialize to JSON, which is working partially, and I got this result:

{
  "Created": "2022-09-13T09:45:05",
  "Version": "1.17.1460",
  "SerialNumber": "2081",
  "Site": "Site",
  "InstallationDate": "0001-01-01T00:00:00",
  "File": null,
  "Name": null,
  "Encoding": null,
  "Decimals": 0,
  "SequenceNumber": 0,
  "StartTime": "0001-01-01T00:00:00",
  "EndTime": "0001-01-01T00:00:00",
  "Total": 0.0,
  "ExpectedTotal": 0.0,
  "Identities": [],
  "Charges": [],
  "Reject": null
}

I'm not sure what could be wrong on the way I map this, but some values just return as null, and the arrays returns with no data. Everything below the 'File' is not workin properly. Tried to another types of elements/attirbutes and they didn't work. I'm quite new with C#, so I'm not sure what to do. Can someoone help me with that?

Cheers.

CodePudding user response:

You can use Edit > Paste Special > Paste XML as Classes in the edit menu if you are using VS. Assuming your XML structure is correct this will give you:

    // 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 Remote
    {

    private RemoteSetup setupField;

    private System.DateTime createdField;

    private string versionField;

    private ushort serialNumberField;

    private string siteField;

    private System.DateTime installationDateField;

    /// <remarks/>
    public RemoteSetup Setup
    {
        get
        {
            return this.setupField;
        }
        set
        {
            this.setupField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public System.DateTime Created
    {
        get
        {
            return this.createdField;
        }
        set
        {
            this.createdField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Version
    {
        get
        {
            return this.versionField;
        }
        set
        {
            this.versionField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public ushort SerialNumber
    {
        get
        {
            return this.serialNumberField;
        }
        set
        {
            this.serialNumberField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Site
    {
        get
        {
            return this.siteField;
        }
        set
        {
            this.siteField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public System.DateTime InstallationDate
    {
        get
        {
            return this.installationDateField;
        }
        set
        {
            this.installationDateField = value;
        }
    }
}

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RemoteSetup
    {

    private RemoteSetupTransaction transactionField;

    private string fileField;

    private string nameField;

    private string encodingField;

    private byte decimalsField;

    /// <remarks/>
    public RemoteSetupTransaction Transaction
    {
        get
        {
            return this.transactionField;
        }
        set
        {
            this.transactionField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string File
    {
        get
        {
            return this.fileField;
        }
        set
        {
            this.fileField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Encoding
    {
        get
        {
            return this.encodingField;
        }
        set
        {
            this.encodingField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte Decimals
    {
        get
        {
            return this.decimalsField;
        }
        set
        {
            this.decimalsField = value;
        }
    }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RemoteSetupTransaction
    {

    private RemoteSetupTransactionIdent[] identitiesField;

    private RemoteSetupTransactionCharges chargesField;

    private uint sequenceNumberField;

    private System.DateTime startTimeField;

    private System.DateTime endTimeField;

    private decimal totalField;

    private decimal expectedTotalField;

    /// <remarks/>
    [System.Xml.Serialization.XmlArrayItemAttribute("Ident", IsNullable = false)]
    public RemoteSetupTransactionIdent[] Identities
    {
        get
        {
            return this.identitiesField;
        }
        set
        {
            this.identitiesField = value;
        }
    }

    /// <remarks/>
    public RemoteSetupTransactionCharges Charges
    {
        get
        {
            return this.chargesField;
        }
        set
        {
            this.chargesField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public uint SequenceNumber
    {
        get
        {
            return this.sequenceNumberField;
        }
        set
        {
            this.sequenceNumberField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public System.DateTime StartTime
    {
        get
        {
            return this.startTimeField;
        }
        set
        {
            this.startTimeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public System.DateTime EndTime
    {
        get
        {
            return this.endTimeField;
        }
        set
        {
            this.endTimeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public decimal Total
    {
        get
        {
            return this.totalField;
        }
        set
        {
            this.totalField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public decimal ExpectedTotal
    {
        get
        {
            return this.expectedTotalField;
        }
        set
        {
            this.expectedTotalField = value;
        }
    }
}

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RemoteSetupTransactionIdent
    {

    private string nameField;

    private byte valueField;

    private string inHierarchyField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte Value
    {
        get
        {
            return this.valueField;
        }
        set
        {
            this.valueField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string InHierarchy
    {
        get
        {
            return this.inHierarchyField;
        }
        set
        {
            this.inHierarchyField = value;
        }
    }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RemoteSetupTransactionCharges
    {

    private RemoteSetupTransactionChargesCharge[] chargeField;

    private byte rejectField;

    private decimal totalField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute("Charge")]
    public RemoteSetupTransactionChargesCharge[] Charge
    {
        get
        {
            return this.chargeField;
        }
        set
        {
            this.chargeField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte Reject
    {
        get
        {
            return this.rejectField;
        }
        set
        {
            this.rejectField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public decimal Total
    {
        get
        {
            return this.totalField;
        }
        set
        {
            this.totalField = value;
        }
    }
    }

    /// <remarks/>
    [System.SerializableAttribute()]
    [System.ComponentModel.DesignerCategoryAttribute("code")]
    [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
    public partial class RemoteSetupTransactionChargesCharge
    {

    private string nameField;

    private string labelField;

    private byte valueField;

    private byte countField;

    private decimal totalField;

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Name
    {
        get
        {
            return this.nameField;
        }
        set
        {
            this.nameField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string Label
    {
        get
        {
            return this.labelField;
        }
        set
        {
            this.labelField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte Value
    {
        get
        {
            return this.valueField;
        }
        set
        {
            this.valueField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public byte Count
    {
        get
        {
            return this.countField;
        }
        set
        {
            this.countField = value;
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public decimal Total
    {
        get
        {
            return this.totalField;
        }
        set
        {
            this.totalField = value;
        }
    }
    }

Of course, such a method requires some work on properties, at least you can see the nesting of classes here. Then your deserialization will look like this:

XmlSerializer serializer = new XmlSerializer(typeof(Remote));
Remote res = new Remote();
using StreamReader reader = new StreamReader(fileLocation);
res = serializer.Deserialize(reader) as Remote;

CodePudding user response:

It's about your model hierarchy. If you don't design your model correctly, you will encounter problems during deserialization.

Please take a look at the revised model structure below.

[XmlRoot("Remote")]
public class Remote
{
    //Remote
    [XmlAttribute(AttributeName = "Created")]
    public string Created { get; set; }

    [XmlAttribute(AttributeName = "Version")]
    public string Version { get; set; }

    [XmlAttribute(AttributeName = "SerialNumber")]
    public string SerialNumber { get; set; }

    [XmlAttribute(AttributeName = "Site")]
    public string Site { get; set; }

    [XmlAttribute(AttributeName = "InstallationDate")]
    public DateTime InstallationDate { get; set; }

    [XmlElement(ElementName = "Setup")]
    public Setup Setup { get; set; }

}

//Setup
public class Setup
{
    [XmlAttribute(AttributeName = "File")]
    public string File { get; set; }

    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }

    [XmlAttribute(AttributeName = "Encoding")]
    public string Encoding { get; set; }

    [XmlAttribute(AttributeName = "Decimals")]
    public int Decimals { get; set; }

    [XmlElement(ElementName = "Transaction")]
    public Transaction Transaction { get; set; }
}


public class Transaction
{
    //Transaction
    [XmlAttribute(AttributeName = "SequenceNumber")]
    public int SequenceNumber { get; set; }

    [XmlAttribute(AttributeName = "StartTime")]
    public DateTime StartTime { get; set; }

    [XmlAttribute(AttributeName = "EndTime")]
    public DateTime EndTime { get; set; }

    [XmlAttribute(AttributeName = "Total")]
    public double Total { get; set; }

    [XmlAttribute(AttributeName = "ExpectedTotal")]
    public double ExpectedTotal { get; set; }

    [XmlArray(ElementName = "Identities")]
    public List<Ident> Identities { get; set; }

    [XmlElement("Charges")]
    public Charges Charges { get; set; }
}

[XmlType("Charges")]
public class Charges
{
    [XmlAttribute(AttributeName = "Reject")]
    public string Reject { get; set; }

    [XmlAttribute(AttributeName = "Total")]
    public double Total { get; set; }
    public List<Charge> ChargeList { get; set; }
}

[XmlType("Charge")]
public class Charge
{
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }

    [XmlAttribute(AttributeName = "Label")]
    public string Label { get; set; }

    [XmlAttribute(AttributeName = "Value")]
    public double Value { get; set; }

    [XmlAttribute(AttributeName = "Count")]
    public int Count { get; set; }

    [XmlAttribute(AttributeName = "Total")]
    public double Total { get; set; }
}

[XmlType("Ident")]
public class Ident
{
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }

    [XmlAttribute(AttributeName = "Value")]
    public int Value { get; set; }

    [XmlAttribute(AttributeName = "InHierarchy")]
    public string InHierarchy { get; set; }
}
  • Related