C# 如何显示 XML?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9124407/
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
how to display XML?
提问by Muhammad Mamoor Khan
WebRequest req = HttpWebRequest.Create("http://example.com/example");
WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string str = sr.ReadToEnd();
XmlDocument doc = new XmlDocument();
doc.LoadXml(str);
XmlTextWriter writer = new XmlTextWriter("D://myGameSite//myGames.xml", null);
writer.Formatting = Formatting.Indented;
doc.Save(writer);**strong text**
Response.Write(doc);
now this code is working perfectly I mean it saves the XML file in the root directory of the myGameSite with the file named myGames, but when I try to display this XML file in browser as you can see in the code, it just plainly displays this
现在这段代码运行良好 我的意思是它将 XML 文件保存在 myGameSite 的根目录中,文件名为 myGames,但是当我尝试在浏览器中显示此 XML 文件时,正如您在代码中看到的那样,它只是简单地显示了这个
System.Xml.XmlDocument
I want to display this XML file in my browser along with the tags, and the version of my asp.net and .netframework is 2.0 so please I can't use LINQ :(
我想在我的浏览器中显示这个 XML 文件和标签,我的 asp.net 和 .netframework 的版本是 2.0 所以我不能使用 LINQ :(
采纳答案by CoderHawk
This will do ;)
这会做;)
Response.Write("<pre><code>" + Server.HtmlEncode(doc.InnerXml) + "</code></pre>");
EDIT
编辑
Or you can display the xml in a textarea
或者你可以在 textarea 中显示 xml
<asp:TextBox ID="txtXml" runat="server" TextMode="MultiLine" Height="500px" Width="600px" />
Code behind
背后的代码
// This will preserve indentation
txtXml.Text = doc.InnerXml;
回答by Timur Sadykov
in your last row use
在你的最后一行使用
Response.Write(doc.InnerXml);
回答by Marc Gravell
Since you have the xml available, as str, just write that:
既然你有 xml 可用,as str,只需写下:
Response.Write(str);
note that this won't include any formatting changes - if you need that, you'll either need to writethe xml again (to the output), or load the file you just wrote. You'll also want to change the response-type to "text/xml". Unrelated, but note you should also closethe writer, ideally with using:
请注意,这不会包括任何格式更改 - 如果您需要,您将需要再次编写xml(到输出),或者加载您刚刚编写的文件。您还需要将响应类型更改为“text/xml”。无关,但请注意,您还应该关闭编写器,最好使用using:
var settings = new XmlWriterSettings();
settings.Indent = true;
using(var writer = XmlWriter.Create(path, settings)) {
doc.Save(writer);
}
You could also repeat the Save:
你也可以重复Save:
using(var writer = XmlWriter.Create(Response.Output, settings)) {
doc.Save(writer);
}
回答by adatapost
Use XmlDatasourceand Data Controls (GridView/Repeator) to show XML document data.
使用XmlDatasource和数据控件 (GridView/Repeator) 显示 XML 文档数据。
<?xml version="1.0" encoding="iso-8859-1"?>
<root>
<foo>
<bar>One</bar>
</foo>
<foo>
<bar>Two</bar>
</foo>
</root>
Markup:
标记:
<asp:XmlDataSource
runat="server"
id="XmlDataSource1"
XPath="root/foo"
DataFile="file.xml" />
<asp:Repeater ID="Repeater1"
runat="server"
DataSourceID="XmlDataSource1">
<ItemTemplate>
<h2>Bar :<%#XPath("bar")%> </h2>
</ItemTemplate>
</asp:Repeater>
回答by adatapost
google "pretty print xml c#"; e.g. http://www.expertcore.org/viewtopic.php?t=1101
谷歌“漂亮的打印 xml c#”;例如http://www.expertcore.org/viewtopic.php?t=1101
you'll find working code, I'm sure. Here's one example: Format XML String to Print Friendly XML String
你会找到工作代码,我敢肯定。这是一个示例:格式化 XML 字符串以打印友好的 XML 字符串
pass doc.OuterXmlto that function that you find; it'll spit out indented xml
传递doc.OuterXml给你找到的那个函数;它会吐出缩进的 xml
set this xml to some multiline textbox in readonly more or some label; unless it's textbox/textarea, you'll have to html-encode it (e.g. for a label):
将此 xml 设置为 readonly more 或某个标签中的某个多行文本框;除非它是文本框/文本区域,否则您必须对其进行 html 编码(例如用于标签):
this.someLabel.Text = this.Server.HtmlEncode(prettyPrintedXml)
this.someLabel.Text = this.Server.HtmlEncode(prettyPrintedXml)
回答by Sergey Malyutin
Try the following code:
试试下面的代码:
public static string IndentedPrint(XmlDocument doc)
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.Unicode))
{
xmlTextWriter.Formatting = Formatting.Indented;
doc.WriteContentTo(xmlTextWriter);
xmlTextWriter.Flush();
memoryStream.Flush();
memoryStream.Position = 0;
using (StreamReader sr = new StreamReader(memoryStream))
{
return sr.ReadToEnd();
}
}
}
}
回答by Charitha Goonewardena
For those who uses C# as back-end and angular as front-end mcv framework the following code will work (kind of a workaround).
对于那些使用 C# 作为后端和 angular 作为前端 mcv 框架的人,以下代码将起作用(一种解决方法)。
[BACK-END]
using Newtonsoft.Json;
using System.Xml;
//-----
public ActionResult QueryGenerator(string naturalQuery)
{
XmlDocument doc = new XmlDocument();
doc.Load(path_to_xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
return Json( new{xmlString = jsonText}, JsonRequestBehavior.AllowGet);
}
[JAVASCRIPT]
$http({
method: 'GET',
url: baseUrl + 'QueryGenerator',
params: params
}).
success(function (data, status, config) {
$scope.xmlList = JSON.parse(data.xmlString);
}).
error(function (data, status, config) {
alert('error');
});
[HTML]
<xmp ng-repeat="node in xmlList track by $index">
<Discource>
<Token>
<Term>{{node.Term}}</Term>
<PosTag>{{node.PosTag}}</PosTag>
<Restriction>{{node.Restriction}}</Restriction>
<Synonyms>{{node.Synonyms}}</Synonyms>
</Token>
</Discource>
</xmp>
回答by D. Kermott
Just use the XMP tag... it will indent and make your xml almost look pretty!
只需使用 XMP 标签...它会缩进并使您的 xml 几乎看起来很漂亮!
<XMP>
<po>
<BeginningSegment_BEG>
<TransactionSetPurposeCode_01>00</TransactionSetPurposeCode_01>
<PurchaseOrderTypeCode_02>NE</PurchaseOrderTypeCode_02>
<PurchaseOrderNumber_03>PO01183082</PurchaseOrderNumber_03>
<Date_05>2016-12-14</Date_05>
</BeginningSegment_BEG>
</po>
</XMP>
and it will look like this in your browser:

It worked for me in Chrome and IE
它在 Chrome 和 IE 中对我有用

