1

I have created an object(Complex object) in c# which I want to send a response from API in XML. How can I set the value to complex nodes and Serialize it in proper XML.

Below is my code..

  1. C# object which I want to convert
[XmlRoot]
[Serializable]
public class Response
{
    private Response headerField;

    private Response bodyField;

    /// <remarks/>
    public Response Header
    {
        get
        {
            return this.headerField;
        }
        set
        {
            this.headerField = value;
        }
    }

    /// <remarks/>
    public Response Body
    {
        get
        {
            return this.bodyField;
        }
        set
        {
            this.bodyField = value;
        }
    }

}

public class Header
{
    public string ACCT_NUM { get; set; }
    public string NIC { get; set; }
    public string requestId { get; set; }
    public string BankId { get; set; }
}

public class Body
{
    public string STATUS { get; set; }
    public Body ERROR { get; set; }
}

public class ERROR
{
    public string ERRORCODE { get; set; }

    /// <remarks/>
    public string ERRORDESC { get; set; }

    /// <remarks/>
    public string ERRORTYPE { get; set; }

}
  1. Serialize code by which I am setting values to fields and sending.


 var header = new Header()
            {
                ACCT_NUM= arr[0].ACCT_NUM.ToString(),
                BankId= arr[0].BankId.ToString(),
                requestId= arr[0].requestId.ToString(),
                NIC= arr[0].NIC.ToString()
            };

            var body = new Body()
            {
                STATUS = "SUCCESS"
            };

using(var stream=new MemoryStream())
{
    XmlSerializer xmlSer=new
    XmlSerializer(typeof(Response));xmlSer.Serialize(stream,new Response()
    {
        Header = header,
        Body = body
    });

    stream.Position = 0;
    using(var reader = new StreamReader(stream, Encoding.UTF8))
    {
        string value = reader.ReadToEnd();
    }
}

Please guide me here how can I achieve to Serialize the object in XML and sent it as response from API.

2
  • Check this : It will help stackoverflow.com/questions/38316358/… Commented Feb 26, 2020 at 6:41
  • Hi @ZeeCode I tried a lot but did not understand. Commented Feb 26, 2020 at 6:46

3 Answers 3

0

You can add xml serialisation support to .net core mvc. This would allow the client to request xml via setting the Accept header.

services.AddMvc(options =>
{
    options.RespectBrowserAcceptHeader = true; // false by default
    .OutputFormatters.Insert(0, new XmlSerializerOutputFormatter());
    options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("application/xml"));
});

Or you can match the response type based on a format argument in the request path;

        [Route("{id}.{format}"), FormatFilter]
        public async Task<IActionResult> Load(int id)
Sign up to request clarification or add additional context in comments.

1 Comment

Hi @Jeremy Lakeman, Yes my post method accepts XML as a request and I am able to to that next challenge for me is to pass response in XML and I have created response according to me ...The above class have created I want that to be my response from API in XML. Formatter will do job but in my case i have object which i need to serialize in xml and pass it simply .
0

You can try this

public string SerializeToString()
    {
        var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
        var serializer = new XmlSerializer(this.GetType());
        var settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;

        using (var stream = new StringWriter())
        using (var writer = XmlWriter.Create(stream, settings))
        {
            serializer.Serialize(writer, this, emptyNamespaces);
            return stream.ToString();
        }
    }

4 Comments

Hi @Fazal Qayyun how can i access complex object mean if you see my start tag is response then header and then there is fields in header.. i need that flow to be generated in xml
Your code only provides me the below XML response. <?xml version="1.0" encoding="utf-16"?> <Response xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema" />
I want my response like as below <Response><Header><A1></A1><A2><A2></Header><Body><B1></B1><E1></E1></Body></Response>
@MayurWaghulde i have updated my answer i hope this will help you. Kindly try now above one.
0

controller get x-www-form-urlencoded body and send request XML or JSON (filter.JSON=true for json response body)

    [HttpPost("getbnprices")]
    [Consumes("application/x-www-form-urlencoded")]
    
    public ActionResult GetBnPricesXForm([FromForm] FilterListApiModel filter)
    {
        filter.UserName = filter.Login;

        try
        {
            if (filter == null)
                return BadRequest();

            var result = _leftoversSupervisor.GetBnPrices(filter).ToList();
            if (result == null) return Ok();
            var Pricelist = new BnPriceListXml<BnPriceApiModel>();
            Pricelist.AddRange(result);

            if (!filter.JSON)
            {

                var xmlOut = XmlSerializerExtension.OutXmlString(Pricelist);
                return new ContentResult
                {
                    ContentType = "text/xml; charset=WINDOWS-1251", //if necessary change charset 
                    Content = xmlOut,
                    StatusCode = 200
                };
            }
            else
            {
                return Ok(Pricelist); // response body in json
            }


        }
        catch (Exception ex)
        {
            return StatusCode(500, ex);
        }
    }

and method for serializing XML from object ( for clean result delete namespaces and change some chars for valid XML document)

    public static string OutXmlString<T>(T items) where T : class
    {
        var xmlString = "";
        var xmlSerializer = new XmlSerializer(items.GetType());
        var xmlSb = new StringBuilder();
        using (var stringWriter = new StringWriter())
        {
            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
            {
                xmlSerializer.Serialize(xmlWriter, items);
                xmlString = stringWriter.ToString();
            }
        }
        string strXMLPatternNamspace = @"[\s]xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
        xmlString = Regex.Replace(xmlString, strXMLPatternNamspace, "");
        xmlSb.Append(xmlString);
        xmlSb.Replace("-", "&#45;");
        xmlSb.Replace(@"""", "&quot;");
        xmlSb.Replace(@"'", "&apos;");
        xmlSb.Replace(@"<?xml version=&quot;1.0&quot; encoding=&quot;utf&#45;16&quot;?>", @"<? xml version = ""1.0"" encoding = ""windows-1251""?>");

        return  xmlSb.ToString();
    }

example output

<?xml version="1.0" encoding="windows-1251"?>
<Pricelist>
    <Product>
        <TypeName>Моноблоки</TypeName>
        <CategoryID>582</CategoryID>
        <ItemType>23.8&quot;</ItemType>
        <ItemCode>365425</ItemCode>
        <Artikul>XA24.HK7.I14.8.S2.N.U.075</Artikul>
        <Vendor>Expert PC</Vendor>
        <ItemName>Персональний комп`ютер&#45;моноблок Expert PC G24h (XA24.HK7.I14.8.S2.N.U.075) White</ItemName>
        <warranty>36</warranty>
        <UCGFEA>8471</UCGFEA>
        <barcode> </barcode>
        <qty>10</qty>
        <price>22265</price>
        <price_RIP>28199</price_RIP>
        <weight></weight>
        <width></width>
        <height></height>
        <depth></depth>
        <volume></volume>
    </Product>
</Pricelist>

maybe need configure your service

    public static void AddControllersWithFormatters(this IServiceCollection services)
    {
        //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        services.AddControllers(options =>
        {
            options.Filters.Add(new ProducesAttribute("application/x-www-form-urlencoded"));
            options.Filters.Add(new ProducesAttribute("application/xml"));
            options.Filters.Add(new ProducesAttribute("text/xml"));
            options.RespectBrowserAcceptHeader = true;
            options.OutputFormatters.Add(new XmlSerializerOutputFormatterNamespace());
            options.OutputFormatters.Add(new XmlSerializerOutputFormatter(new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                OmitXmlDeclaration = false
            }));
        }).AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        }).AddXmlSerializerFormatters();
        //.AddXmlDataContractSerializerFormatters();
    }

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.