How to serialize objects into XML C#

Kumar, Sumant 96 Reputation points
2021-06-29T20:18:16.107+00:00

I have written a simple webAPI program which returns JSON by default when running , I want the values in XML format so I tried below code it always returns string for me, have also tried multiple solution from this stackoverflow post but all returns string.

Model class:

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
namespace JsonToXML2.Models  
{  
    public class Employee  
    {  
        public int EmployeeId  
        {  
            get;  
            set;  
        }  
        public string EmployeeName  
        {  
            get;  
            set;  
        }  
        public string Address  
        {  
            get;  
            set;  
        }  
        public string Department  
        {  
            get;  
            set;  
        }  
    }  
}  

Controller Class :

using Newtonsoft.Json;  
using System;  
using System.Collections.Generic;  
using System.IO;  
using System.Linq;  
using System.Net;  
using System.Net.Http;  
using System.Text;  
using System.Web.Http;  
using System.Xml;  
using System.Xml.Serialization;  
  
namespace JsonToXML2.Controllers  
{  
    public class EmployeeController : ApiController  
    {  
        IList<Employee> employees = new List<Employee>()  
        {  
            new Employee()  
                {  
                    EmployeeId = 1, EmployeeName = "Mukesh Kumar", Address = "New Delhi", Department = "IT"  
                },  
                new Employee()  
                {  
                    EmployeeId = 2, EmployeeName = "Banky Chamber", Address = "London", Department = "HR"  
                },  
                new Employee()  
                {  
                    EmployeeId = 3, EmployeeName = "Rahul Rathor", Address = "Laxmi Nagar", Department = "IT"  
                },  
                new Employee()  
                {  
                    EmployeeId = 4, EmployeeName = "YaduVeer Singh", Address = "Goa", Department = "Sales"  
                },  
                new Employee()  
                {  
                    EmployeeId = 5, EmployeeName = "Manish Sharma", Address = "New Delhi", Department = "HR"  
                },  
        };  
        public IList<Employee> GetAllEmployees()  
        {  
            //Return list of all employees    
            return employees;  
        }  
        public String GetEmployeeDetails(int id)  
        {  
            //Return a single employee detail    
            var employee = employees.FirstOrDefault(e => e.EmployeeId == id);  
            if (employee == null)  
            {  
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));  
            }  
              
             
            return (GenerateXmlResponse(employee));  
        }  
        // override StringWriter  
        public class Utf8StringWriter : StringWriter  
        {  
            public override Encoding Encoding => Encoding.UTF8;  
        }  
  
        private string GenerateXmlResponse(Object obj)  
        {  
            Type t = obj.GetType();  
  
            var xml = "";  
  
            using (StringWriter sww = new Utf8StringWriter())  
            {  
                using (XmlWriter writer = XmlWriter.Create(sww))  
                {  
                    var ns = new XmlSerializerNamespaces();  
                    // add empty namespace  
                    ns.Add("", "");  
                    XmlSerializer xsSubmit = new XmlSerializer(t);  
                    xsSubmit.Serialize(writer, obj, ns);  
                    xml = sww.ToString(); // Your XML  
                }  
            }  
            return xml;  
        }  
    }  
}  

To access the app I am simply hitting the URL as https://localhost:44379/api/employee/1 in postman, the problem is data is in String format within double quotes, How can I get the data in pure XML format?

110318-image.png
110319-image.png

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,311 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
303 questions
{count} votes

Accepted answer
  1. Kumar, Sumant 96 Reputation points
    2021-06-30T09:55:36.21+00:00

    One of the solution was to ask clients to set request header "Accept: text/xml"

    Since I couldn't force the client, what I can do at my end is to set my method return type as System.Net.Http.HttpResponseMessage and use the below code to return the XML.

       public HttpResponseMessage Authenticate()  
       {  
         //process the request   
         .........  
         
         string XML="<note><body>Message content</body></note>";  
         return new HttpResponseMessage()   
         {   
           Content = new StringContent(XML, Encoding.UTF8, "application/xml")   
         };  
       }  
    

    110631-image.png


1 additional answer

Sort by: Most helpful
  1. Yijing Sun-MSFT 7,071 Reputation points
    2021-06-30T02:27:05.137+00:00

    Hi @Kumar, Sumant ,
    As far as I think,you could set xml format in global.asax. You can use XmlSerializer for the object .
    Just like this:

    var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;  
    // Use XmlSerializer for instances of type "Product":  
    xml.SetSerializer<employees>(new XmlSerializer(typeof(employees)));  
    

    More details,you could refer to below articles:
    https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/json-and-xml-serialization
    https://stackoverflow.com/questions/51391985/return-xml-from-web-api
    Best regards,
    Yijing Sun


    If the answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our  documentation  to enable e-mail notifications if you want to receive the related email notification for this thread.