我有一个控制台应用程序,它读取XML文件并将所有内容输出到控制台中。 我需要转换此应用程序以在.aspx页面上输出数据。
这是代码
// Declare XmlTextReader.
XmlTextReader r = new XmlTextReader("../../persons.xml");
while (r.Read())
{
switch (r.NodeType)
{
case XmlNodeType.Element:
if (r.Name == "Persons")
{
Console.WriteLine("<table>");
Console.WriteLine(" <tr> <th>Name</th> <th>Gender</th> <th>Age</th> </tr>");
}
else if (r.Name == "Person")
{
Console.Write(" <tr> ");
}
else if (r.Name == "Name" ||
r.Name == "Gender" || r.Name == "Age")
{
Console.Write("<td>");
}
break;
case XmlNodeType.Text:
Console.Write(r.Value);
break;
case XmlNodeType.EndElement:
if (r.Name == "Persons")
{
Console.WriteLine("</table>\n");
}
else if (r.Name == "Person")
{
Console.Write("</tr>\n");
}
else if (r.Name == "Name" ||
r.Name == "Gender" || r.Name == "Age")
{
Console.Write(">/td> ");
}
break;
}
}
我发现了许多关于如何使用ASP.NET读取XML的示例,但不幸的是我需要这么做。
答案 0 :(得分:2)
您可以考虑一些替代方案
覆盖Console
的默认输出StringWriter sw = new StringWriter(); Console.SetOut(SW);
所有输出都将存储在sw变量
中答案 1 :(得分:2)
您需要在.aspx页面上添加文字控件,如下所示:
<asp:Literal ID="Literal1" runat="server" />
然后像这样修改代码:
// Declare XmlTextReader.
XmlTextReader r = new XmlTextReader("../../persons.xml");
//Add this stringBuilder
StringBuilder sb = new StringBuilder();
while (r.Read())
{
switch (r.NodeType)
{
case XmlNodeType.Element:
if (r.Name == "Persons")
{
sb.Append("<table>");
sb.Append(" <tr> <th>Name</th> <th>Gender</th> <th>Age</th> </tr>");
}
else if (r.Name == "Person")
{
sb.Append(" <tr> ");
}
else if (r.Name == "Name" ||
r.Name == "Gender" || r.Name == "Age")
{
sb.Append("<td>");
}
break;
case XmlNodeType.Text:
sb.Append(r.Value);
break;
case XmlNodeType.EndElement:
if (r.Name == "Persons")
{
sb.Append("</table>\n");
}
else if (r.Name == "Person")
{
sb.Append("</tr>\n");
}
else if (r.Name == "Name" ||
r.Name == "Gender" || r.Name == "Age")
{
sb.Append(">/td> ");
}
break;
}
}
//Add the result value to a literal control on the aspx page
Literal1.Text=sb.ToString();
欢呼声