【发布时间】:2012-04-08 18:41:39
【问题描述】:
我想读取一个 XML 文件,然后将其显示到网页上,但我无法在 for 循环中执行此操作
XmlDocument doc = new XmlDocument();
doc.Load(@"c:/xmldatabase.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//User");
foreach (XmlNode node in nodes)
{
Label1.Text = node["Name"].InnerText;
Label3.Text = node["Contact"].InnerText;
Label4.Text = node["Email"].InnerText;
Label2.Text = node["City"].InnerText;
Label5.Text = node["Country"].InnerText;
}
我的 XML 有数据!
<?xml version="1.0"?>
<User-Profile>
<User>
<Name>Jhon</Name>
<Contact>4567897632</Contact>
<Email>pri@dfdcm.com</Email>
<City>xyz</City>
<Country>abc</Country>
</User>
<User>
<Name>Mike</Name>
<Contact>8888888</Contact>
<Email>acvb@dfdcm.com</Email>
<City>xrtty</City>
<Country>abffff</Country>
</User>
<User>
<Name>Stone</Name>
<Contact>875467</Contact>
<Email>dfttgh@dfdcm.com</Email>
<City>dfvbnj</City>
<Country>ddccvv</Country>
</User>
</User-Profile>
我想使用循环或任何东西显示所有数据并将这些数据分配给我的网页标签,这可能吗?如何做到这一点?
【问题讨论】:
-
有什么理由不使用 LINQ to XML?它可能会让一切变得更简单......
-
我不知道 LINQ to XML 是否容易,你能告诉我我的案例示例,阅读 xml 并在网页标签中打印整个结果
-
LINQ 是最好的选择,而且容易得多,但在您的代码中,您可能会在标签中显示最后一次迭代的值。如果必须在标签中显示记录,则应在循环中创建它们并将它们添加到网页中
-
您看到了什么错误?程序在哪里崩溃?什么不工作?
-
好吧,即使你有 10'000 个节点用于
//Users- 你不断为那些固定的 5 个标签设置.Text值,一遍又一遍……什么您需要更改的是如何显示数据(读数很好)-您需要一个列表框或列表视图或网格或可以显示数据列表的东西-不仅仅是五个固定标签一组文本
标签: c# asp.net .net xml webforms