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?

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=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n  <soap:Body>\r\n    <EnclosedBody xmlns=\"https://DomainName.com/\">\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;

        }

Edit this Article
Web-Service Asp.Net Core 3.1 XML C Technology published
Was this page helpful?
Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful.. Leave ErnesTech Feedback.Feedback
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

Your Session is Ending
Login to Continue

© 2021 - ErnesTech - Privacy