Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning XML from web API c#

newbie here as long as web API is concerned.

web Api:

[HttpGet]
    public IHttpActionResult Test()
    {
        var doc = new XmlDocument();
        XmlElement tournament = (XmlElement)doc.AppendChild(doc.CreateElement("Tournament"));
        XmlElement match = (XmlElement)tournament.AppendChild(doc.CreateElement("Match"));
        match.SetAttribute("ID", "SomeMatch");

        return Ok(doc.InnerXml);
    }

Result:

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">&lt;Tournament&gt;&lt;Match ID="SomeMatch" /&gt;&lt;/Tournament&gt;</string>

Two problems:

  1. why it is wrapped in this string element when my XML does not have it?
  2. why < is converted to "& lt;" and > to "& gt;"

and how to get back just

<Tournament>
<Match ID="SomeMatch" /></Tournament>
like image 722
ahsant Avatar asked Sep 12 '26 08:09

ahsant


2 Answers

Since you are returning a string from the action, ASP.Net Web API is creating the equivalent XML to represent a string.

Now, if you were to ensure that API uses XML serialization, client can add accept header to the request. Alternatively, you can specify the formatter either the way you have or in the action itself by returning Content using following constructor:

return Content (HttpStatusCodeHere, doc.DocumentElement, Configuration.Formatters.XmlFormatter)

Note that I do not have access to Visual Studio so class/property names might not be accurate.

like image 93
danish Avatar answered Sep 13 '26 21:09

danish


You have to returns doc.DocumentElement instead of doc.InnerXml.

Because doc.InnerXml gives you xml in string format that's why your xml is shown in <string> format

[HttpGet]
        public IHttpActionResult Test()
        {
            var doc = new XmlDocument();
            XmlElement tournament = (XmlElement)doc.AppendChild(doc.CreateElement("Tournament"));
            XmlElement match = (XmlElement)tournament.AppendChild(doc.CreateElement("Match"));
            match.SetAttribute("ID", "SomeMatch");
            return Ok(doc.DocumentElement);                 
        }

All your api(s) returns output is in xml format because your HttpConfiguration set in XmlFormatter by default.

like image 38
er-sho Avatar answered Sep 13 '26 21:09

er-sho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!