How to return XML from an ASPX page

I have an object and you want to convert it to XML and show it on the page in raw format.

Desired Conclusion

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

The 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 the same.

100 test

What should I do to get the desired result.

+4
source share
2 answers

I assume the browser simply ignores the XML tags. try this instead:

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

Read here about the HTMLEncode method.

settings.OmitXmlDeclaration = true;must remove the tag <?xml version.... If this does not work, you can try the following: load the xmlString into the object XDocumentand delete its declaration (based on this answer) :

XDocument xdoc = XDocument.Parse(xmlString);
xdoc.Declaration = null;
Response.Write (Server.HTMLEncode(xdoc.ToString()));
+3
source

, XML HTML, " tag soup" HTML-.

.

HTML, XML. , , , , XML, ASP.NET WebForms?

Response.ContentType = "application/xml";

, XML. xml xml- MSDN: XmlWriterSettings.OmitXmlDeclaration:

XML , ConformanceLevel Document, OmitXmlDeclaration true.

XML , ConformanceLevel Fragment

settings.ConformanceLevel ConformanceLevel.Fragment. , XML- , .

+5

All Articles