【问题标题】:Xml file reading by its node c#通过其节点c#读取xml文件
【发布时间】: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


【解决方案1】:

你应该做的是使用中继器。然后,您可以在 foreach 循环中为每个用户添加一个列表,并使用该列表填充您的转发器。有关中继器以及如何填充它们的详细信息,请参阅http://msdn.microsoft.com/en-us/magazine/cc163780.aspx

【讨论】:

    【解决方案2】:

    请在 c# 中使用“PlaceHolder”。您可以轻松拖放 PlaceHolder :) 然后使用此代码

    foreach (XmlNode node in nodes)
    {
      PlaceHolder1.Controls.Add(new LiteralControl("<table><tr><td>" + node["Name"].InnerText + "</td><td>"+node["Contact"].InnerText+"</td><td>"+node["Email"].InnerText+"</td><td>"+node["City"].InnerText+"</td><td>"+node["Country"].InnerText+"</td></tr></tabel>")); 
    }
    

    重要:- 代码上面缺少一些文本。请与下图比较。然后您可以开发最佳代码。 :) Image

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      相关资源
      最近更新 更多