Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return XML from an ASPX page

Tags:

c#

I have an object and would like to convert it into XML and show it on page in its raw format.

Desired output

<Response>
 <ResponseCode>100</ResponseCode>
 <ResponseDescription>Test</ResponseDescription>
</Reponse>

Code:

public class Response
{
    public Response(){}

    public string ResponseCode { get; set; }        
    public string ResponseDescription { get; set; }
}

Page_Load()
{
 Response obj = new Response();
 obj.ResponseCode = "100";
 obj.ResponseDescription = "test";

 string xmlString;
 XmlSerializer serializer = new XmlSerializer(typeof(Response));
 XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
 // exclude xsi and xsd namespaces by adding the following:
 ns.Add(string.Empty, string.Empty);

 using (StringWriter textWriter = new StringWriter())
  {
   using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
    {
      serializer.Serialize(xmlWriter, obj, ns);
    }
   xmlString = textWriter.ToString(); 
  }    
  Response.Write(xmlString);
}

The result is just like this.

100 test

What should I do to get the desired output.

like image 586
Qwerty Avatar asked Feb 07 '23 15:02

Qwerty


2 Answers

The actual problem is that you're outputting XML as HTML, causing your browser to treat the response as "tag soup" and try to render it as an HTML document.

This hides all tags and their attributes, and only renders the text inside and between tags.

This isn't HTML, it's XML. So the actual solution is to set the proper content-type, indicating that you're actually returning XML, from How do you specify your Content Type in ASP.NET WebForms?:

Response.ContentType = "application/xml";

Additionally, you're asking to omit the XML declaration. From how to create an xml using xml writer without declaration element and MSDN: XmlWriterSettings.OmitXmlDeclaration:

The XML declaration is always written if ConformanceLevel is set to Document, even if OmitXmlDeclaration is set to true.

The XML declaration is never written if ConformanceLevel is set to Fragment

So simply set the settings.ConformanceLevel to ConformanceLevel.Fragment. Note that then you're technically not writing an XML document anymore, but this requirement is common in interoperability.

like image 113
CodeCaster Avatar answered Feb 16 '23 04:02

CodeCaster


I'm guessing the browser simply ignores the XML tags. try this instead:

Response.Write (Server.HTMLEncode(xmlString));

Read here about the HTMLEncode method.

the settings.OmitXmlDeclaration = true; should have removed the <?xml version... tag. If that didn't work, you can try this: load the xmlString into an XDocument object and remove it's declaration (based on this answer):

XDocument xdoc = XDocument.Parse(xmlString);
xdoc.Declaration = null;
Response.Write (Server.HTMLEncode(xdoc.ToString()));
like image 33
Zohar Peled Avatar answered Feb 16 '23 04:02

Zohar Peled