Search code examples
c#xmlserializationdeserialization

Handling Different XML Element Names for Serialization and Deserialization in C#


I need advice on handling XML serialization and deserialization in C#. My issue is that I receive XML with elements starting with uppercase letters (e.g., <Id>) for deserialization, but I need to get lowercase letters (e.g., <id>) for serialization.

Is there a way to handle these naming differences, other than xslt or custom serializer?

Example class:

[XmlRoot(ElementName = "Invoice")]
public class Invoice
{
    [XmlElement(ElementName = "Id")]
    public int Id { get; set; }

    [XmlElement(ElementName = "User-id")]
    public int UserId { get; set; }
    
    // more properties

}

Edit

My case

I need to read xml from db with first letters big

<Invoice><Id>1</Id><User-id>1</User-id></Invoice>

In the tags and pass it in the body request but with lowercase letters in the tags

<invoice><id>1</id><user-id>1</user-id></invoice>.


Solution

  • This may not be a good solution for everyone, in the RestSharp library I found attributes such as

    
    [DeserializeAs(Name = "...")]
    [SerializeAs(Name = "...")]
    
    

    In my case it look like this

    
        [SerializeAs(Name = "invoice")]
        [XmlRoot(ElementName = "Invoice")]
        public class invoice
        {
            [SerializeAs(Name = "id")]
            [XmlElement(ElementName = "Id")]
            public int id { get; set; }
    
            [SerializeAs(Name = "user-id")]
            [XmlElement(ElementName = "User-id")]
            public int userId { get; set; }
    
            // more properties
    
        }
    
    

    from this model i get xml like

    <invoice>
      <id>1</id>
      <user-id>1</user-id>
    </invoice>
    

    For this to work, there are requirements

     [XmlRoot(ElementName = "...")]
     [XmlElement(ElementName = "...")]