在iframe中显示来自URL的原始XML

10

我在我的Web服务器上有一个XML文件,当我尝试在浏览器中打开它时,它以原始的XML格式正确显示,但是当我尝试使用其URL在iframe中显示时,它会以字符串形式而不是原始的XML格式显示。

<iframe type="application/xml" src="http://www.w3schools.com/xml/simple.xml"></iframe>

请注意,我无法在 iframe 中将 xml 作为内容加载,因为该 xml 是动态生成的,我只能使用其 url 在 iframe 中加载。

http://jsfiddle.net/qvRzT/8/

2个回答

2
在我的情况下,来自API响应的XML源将传递给HTML iframe标签源。响应内容类型text/plain将在html页面中显示未解析的纯文本XML内容。
HTML
<iframe type="text/plain" data-bind="attr: {src: ('api/document/view?token=' + doc.downloadUrl)}"></iframe>

C# API响应

public HttpResponseMessage View(string token)
{
        HttpResponseMessage result = null;
         var localFilePath ="D:\sample.xml";
        var fileInfo = new System.IO.FileInfo(localFilePath);
        result = Request.CreateResponse(HttpStatusCode.OK);
        result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
        string FileMimeType = MimeMapping.GetMimeMapping(fileInfo.Name);
        if (FileMimeType == "text/xml")
        {
             result.Content.Headers.ContentType = new 
             System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
         }
         else
              result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(FileMimeType);
         result.Content.Headers.ContentDisposition = new 
         System.Net.Http.Headers.ContentDispositionHeaderValue("inline");
         result.Content.Headers.ContentDisposition.FileName = fileInfo.Name;
         return result;
 }

1
在iframe元素中设置属性type="text/plain"对我没有任何影响。但是在响应中设置响应头"Content-Type"为"text/plain"就解决了问题。 - S. Doe

1
这是因为浏览器将XML视为页面的源代码。因此,它将被标记为XML文件。当浏览器获取iframe并加载XML时,它会将源代码处理为HTML(即使没有提供HTML标签)。

3
你有什么建议解决这个问题吗? - Josef Bláha
避免使用 iframe 来显示 XML。相反,导航到 XML。 - leondepdelaw
你的意思是“导航到 XML”是什么? - Karina Klinkevičiūtė
导航到包含XML文件的页面:例如; https://example.net/file.xml 或在这种情况下:http://www.w3schools.com/xml/simple.xml - leondepdelaw
1
有没有其他方法可以在iframe src中显示原始XML内容的HTML页面? - Jayakumar Thangavel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接