Home > database >  How can we have dynamic xml element name in C# class file?
How can we have dynamic xml element name in C# class file?

Time:03-13

This is my current XML Response tag

<Response_Data_1234 diffgr:id="Response_Data_1234" msdata:rowOrder="0" diffgr:hasChanges="inserted">
<Status>File received.</Status>
<Time>2022-01-25T09:44:15.73 08:00</Time>
<Location>HKG</Location>
</Response_Data_1234>

the number 1234 in <Response_Data_1234> is a Response Data id, which will be dynamic depending on the request. Could someone please me create a C# class in this scenario so that I can map the response directly to the class. Thanks in advance

CodePudding user response:

Actually you should not have any unique identifier attached to XML element name. It should be added as attribute.

To answer your question: There is no direct class attribute to ignore class name while deserialisation of xml string to object.

Option1 (better): Create mapper extension method for XNode to class attribute mapping and reuse it.

Option2: If your xml string is small you can try to update name of root element and use it to deserialise.

sample code:


    var responseDataXDoc = XDocument.Parse(xml);
    responseDataXDoc.Root.Name = "ResponseData";

    var serializer = new XmlSerializer(typeof(ResponseData));
    var responseData = serializer.Deserialize(new StringReader(responseDataXDoc.ToString(SaveOptions.DisableFormatting)));

CodePudding user response:

With Cinchoo ETL - an open source library, you can deserialize such xml easily as below

using (var r = ChoXmlReader<ResponseData>.LoadText(xml)
       .WithXPath("//")
       .WithXmlNamespace("diffgr", "")
       .WithXmlNamespace("msdata", "")
      )
{
    var rec = r.FirstOrDefault();
    rec.Print();
}

public class ResponseData
{
    public string Status { get; set; }
    public DateTime Time { get; set; }
    public string Location { get; set; }
}

Sample fiddle: https://dotnetfiddle.net/HOOPOg

  • Related