question

KumarSumant-7724 avatar image
0 Votes"
KumarSumant-7724 asked oliverrc edited

How to serialize objects into XML C#

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


dotnet-csharpdotnet-aspnet-webapi
image.png (25.3 KiB)
image.png (25.3 KiB)
· 5
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


Did you check the Raw tab?



0 Votes 0 ·

Yes, it's same, within double quotes110431-image.png.


0 Votes 0 ·
image.png (32.7 KiB)

Is it something related to MediaTypeFormatter ?


0 Votes 0 ·
Show more comments

The .NET Framework WebAPI 2 by default will serialize responses from a controller method using the built in serializers.
Out the box it supports JSON and XML.

There should be no real reason to manually have to serialize the objects yourself.

     public Employee 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 employee;
          }

In Postman if you set the Accept header to application/xml you should get your Employee object serialized as xml back in the response.

0 Votes 0 ·
KumarSumant-7724 avatar image
0 Votes"
KumarSumant-7724 answered AgaveJoe edited

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





image.png (19.3 KiB)
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The problem with your initial post is you specifically returns a string. Simply return the type and let the serialize handle the response.

the Web API 2 framework defaults to XML but uses the client's accept header to determine the return type format. If XML is required for every response then configure Web API to always return XML. This should NOT be done in the action since it is just configuration.

ASP.NET Core defaults to JSON. For Core, you must configure an XML serializer in the startup.cs file.


0 Votes 0 ·
YijingSun-MSFT avatar image
0 Votes"
YijingSun-MSFT answered KumarSumant-7724 commented

Hi @KumarSumant-7724 ,
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://docs.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.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @YijingSun-MSFT, adding the formatter option in global.asax doesn't do anything, but if we add

`config.Formatters.Remove(config.Formatters.JsonFormatter);` ``

in WebAPiConfig then it converts the data to xml but still in <string> format.

<string>&lt;?xml version="1.0" encoding="utf-16"?&gt;&lt;Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;EmployeeId&gt;1&lt;/EmployeeId&gt; &lt;EmployeeName&gt;Mukesh Kumar&lt;/EmployeeName&gt; &lt;Address&gt;New Delhi&lt;/Address&gt; &lt;Department&gt;IT&lt;/Department&gt;&lt;/Employee&gt;</string>```



0 Votes 0 ·