如何在Web浏览器中显示XML数据?

时间:2017-08-09 09:55:17

标签: c# asp.net xml data-binding web-applications

我从数据库中获取数据。其中一个字段包含XML格式的请求数据。我没有在列中显示它,而是在该单元格中放置了一个按钮,单击该按钮,我希望在浏览器中加载XML数据。 怎么实现呢? 我知道如何在浏览器中从XML文件中加载数据(如果它放在本地,但是如何在浏览器或弹出窗口中显示而不是按钮单击,如果我将其作为查询的结果?

Current View

单击View XML后,它应该在Web浏览器中显示XML数据。

要从文件中显示它,我正在使用此

<asp:Button ID="btnViewXML" class="btn btn-warning btn-xs" runat="server" 
                    Text="View XML" OnClick="ViewXML" />

protected void ViewXML(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/xml";
        Response.WriteFile(Server.MapPath("~/requestData.xml"));
        Response.Flush();
        Response.End();
    }

1 个答案:

答案 0 :(得分:1)

当你说request data in XML format你是指数据库字段中的xml内容,还是xml中的当前http请求?

我假设第一个,那就是数据库字段。

view xml按钮上,传入行唯一ID,然后回发从数据库中获取xml,然后将其写入响应。

类似的东西:

// pass in the row id in command argument

<asp:Button ID="btnViewXML" class="btn btn-warning btn-xs" runat="server" 
                    Text="View XML"  CommandArgument='<%= row.Id %>' OnCommand="ViewXML" />


protected void ViewXML(object sender, CommandEventArgs e)
{
    // id of row
    string id =e.CommandArgument.ToString();
    // fetch from db to get your xml content
    string xmlContent = ...;


    Response.Clear();
    Response.Buffer = true;
    Response.Charset = "";
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/xml";
    Response.Write(xmlContent);
    Response.Flush();
    Response.End();
}

如果我的假设是错误的,那么你必须将你的http请求存储在某处,所以当回发时你可以检索它。无论哪种方式,逻辑几乎都是一样的,只是在你获得xml内容不同的地方。

使用弹出窗口的进一步说明

网上有很多不同的弹出窗口小部件

我使用jquery ui作为示例,您可以使用具有大致相同逻辑的其他弹出窗口小部件

在编写弹出窗口之前,需要考虑的一件事是如何传递数据(在你的情况下是xml结果)。

有两种方式:

  1. 使用第一次请求将您的内容保存在页面的某个位置
  2. 仅在按钮单击时使用ajax加载
  3. 我将使用第一种方式作为示例

    在你的页面上,创建一个div,它将保存你的弹出内容,并在没有打开的情况下使用对话框启动它,并创建一个显示弹出窗口的函数

    <script>
    $(function() {
    
        $('#dialog').dialog({
            autoOpen: false        
        });
    }
    
    function showPopup(content){
        $('#dialog').text(content);
        $('#dialog').dialog("open");
    }
    </script>
    
    <div id="dialog" title="Xml Result">
    </div>
    

    然后当您渲染按钮时,添加一个客户端按钮单击以触发弹出窗口

    <asp:Button ID="btnViewXML" class="btn btn-warning btn-xs" runat="server" 
                        Text="View XML"  onclientclick="showPopup('<%: row.XmlResult%>')"/>
    

    依赖于结果数据的大小以及用户单击视图xml结果的机会,使用ajax可能会提供更好的性能

相关问题