C# 在 ASP.NET 页面上显示 XML 的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/350314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Easiest way to display XML on an ASP.NET page
提问by Ryan Lundy
I have some XML in an XmlDocument, and I want to display it on an ASP.NET page. (The XML should be in a control; the page will have other content.) Right now, we're using the Xml control for that. Trouble is, the XML displays with no indentation. Ugly.
我在 XmlDocument 中有一些 XML,我想在 ASP.NET 页面上显示它。(XML 应该在一个控件中;页面将有其他内容。)现在,我们为此使用 Xml 控件。问题是,XML 显示时没有缩进。丑陋的。
It appears that I'm supposed to create an XSLT for it, but that seems kind of boring. I'd rather just throw it into a control and have it automagically parse the XML and indent correctly. Is there an easy way to do that?
看来我应该为它创建一个 XSLT,但这似乎有点无聊。我宁愿把它扔到一个控件中,让它自动解析 XML 并正确缩进。有没有简单的方法来做到这一点?
采纳答案by devio
You could try to use XmlWriter/XmlTextWriter, set the writer's Indentation property, write to a StringBuilder or MemoryStream, and output the result inside a <pre> tag
您可以尝试使用 XmlWriter/XmlTextWriter,设置 writer 的 Indentation 属性,写入 StringBuilder 或 MemoryStream,并将结果输出到 <pre> 标签中
回答by Stephen Wrighton
A quick (and dirty) way of doing this would be to use an IFrame.
一种快速(且肮脏)的方法是使用 IFrame。
In truth, an XSLT is the "ideal" way for formatting an XML for display. Another option would be to parse it manually for display.
事实上,XSLT 是格式化用于显示的 XML 的“理想”方式。另一种选择是手动解析它以进行显示。
To use an Iframe: ASPX side:
要使用 Iframe:ASPX 端:
< iframe runat="server" id="myXMLFrame" src="~/MyXmlFile.xml" /></pre>
Code Side:
代码端:
myXMLFrame.src = Page.ResolveClientUrl("~/MyXmlFile.xml")
回答by user20259
You can find a slightly modified version of the XSLT that IE uses to transform XML to HTML when viewing in IE at http://www.dpawson.co.uk/xsl/sect4/N10301.html#d15977e117.
您可以在http://www.dpawson.co.uk/xsl/sect4/N10301.html#d15977e117 中找到在 IE 中查看时 IE 用来将 XML 转换为 HTML 的 XSLT 的稍微修改版本。
I have used it in a WebBrowser control in a WinForms application, and it works lika a charm. I have not tested it in FireFox/Chrome/Safari/Operat, though.
我已经在 WinForms 应用程序的 WebBrowser 控件中使用了它,它的工作原理非常棒。不过,我还没有在 FireFox/Chrome/Safari/Operat 中测试过它。