How to Deserialize XML into Object in Asp.Net Core 3.1

Question: How do you Deserialize XML String into a C# Object in Asp.Net Core 3.1?

Login to See the Rest of the Answer


1. First Call the Web Service
2. Insert a Break-Point where you could get the Response String from the Web Service
3. Create a POCO Class Model so that you could Deserialize the XML String into C-Sharp Object
- The way you do this is by creating a brand new class, then go to "Edit" in Visual Studio 2019. Navigate to "Paste Special" in the Drop-Down menu, then click on "Paste XML as Class".
- This will create the C-Sharp Class automatically from XML String you got from the Response.
4. After step 3, it's time to Deserialize the XML String into C-Sharp Object. Simply call "new XmlSerializer(typeof(YourPocoClassModelYouCreated)) to get the object.

5. See the code below:

  public async Task<POCOModelClass> callWebService()
            var client = new RestClient("urlHere");
            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "text/xml");
//This is the payload if required
            request.AddParameter("text/xml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<soap:Envelope xmlns:xsi=\"\" xmlns:xsd=\"\" xmlns:soap=\"\">\r\n  <soap:Body>\r\n    <EnclosedBody xmlns=\"\">\r\n      <param1>SomeParam</param1>\r\n      <param2>SomeParam</param2>\r\n      <param3>SomeParam</param3>\r\n    </EnclosedBody>\r\n  </soap:Body>\r\n</soap:Envelope>", ParameterType.RequestBody);
            IRestResponse response = await client.ExecuteAsync(request);

            var serializer = new XmlSerializer(typeof(POCOModelClass));
            POCOModelClass result;
            using (TextReader reader = new StringReader(response.Content.ToString()))
                result = (POCOModelClass)serializer.Deserialize(reader);
            return result;


© 2024 - ErnesTech - Privacy
E-Commerce Return Policy