gpt4 book ai didi

c# - 如何从 ASPX 页面返回 XML

转载 作者:太空狗 更新时间:2023-10-30 00:30:30 25 4
gpt4 key购买 nike

我有一个对象,想将它转换成 XML 并以原始格式在页面上显示它。

期望的输出

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

代码:

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);
}

结果就是这样

100 test

我应该怎么做才能获得所需的输出。

最佳答案

实际问题是您将 XML 输出为 HTML,导致您的浏览器将响应视为“tag soup”并尝试将其呈现为 HTML 文档。

这会隐藏所有标签及其属性,并且只呈现标签内部和标签之间的文本。

这不是 HTML,而是 XML。所以实际的解决方案是设置正确的内容类型,表明您实际上是从 How do you specify your Content Type in ASP.NET WebForms? 返回 XML :

Response.ContentType = "application/xml";

此外,您是 asking to omit the XML declaration .来自 how to create an xml using xml writer without declaration elementMSDN: 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

因此只需将 settings.ConformanceLevel 设置为 ConformanceLevel.Fragment。请注意,从技术上讲,您不再编写 XML 文档,但这种要求在互操作性方面很常见。

关于c# - 如何从 ASPX 页面返回 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35725572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com