如何在视图中显示所有特定的XML元素? [英] How do I get all specific XML elements to show in view?

查看:68
本文介绍了如何在视图中显示所有特定的XML元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些数据的XML文件,想要在Controller中通过标签名称ProjectNr检索所有元素,然后将列表发送到View,在下拉列表中显示项目编号。



以下代码的问题是它只显示ProjectNr的最后一个元素,这意味着它会覆盖每个元素,直到它到达循环结束,然后只剩下最后一个元素。



我试图让它保存所有元素,但似乎没有任何工作。我是C#的新手,所以我确信我错过了一些简单的东西或做了一些完全错误的事情。 ;-)



这有什么意义吗?



XML树看起来像这样:



I have a XML file with some data and want to retrieve all elements by the tag name of "ProjectNr" in Controller and then send the list to View showing the project numbers in a dropdownlist.

The problem with below code is that it only shows the last element of "ProjectNr" which means it overwrites each element until it reaches the end of the loop and then only the last remains.

I have tried to make it save all the elements but nothing seems to be working. I am fairly new to C# so I am sure Im missing something simple or doing something completely wrong. ;-)

Does this make any sense?

The XML tree looks like this:

<Activities>
  <Activity>
    <ActivityName>Projekt</ActivityName>
    <ProjectNr>001</ProjectNr>
  </Activity>
  <Activity>
    <ActivityName>Absence</ActivityName>
    <ProjectNr>000</ProjectNr>
  </Activity>
</Activities>





控制器代码:





Code in Controller:

public ActionResult NewActivity()
{
   XElement xelement = XElement.Load(Server.MapPath("/App_Data/ActivitiesData.xml"));
   IEnumerable<XElement> Activity = xelement.Elements();

   foreach (var ProjNrList in Activity)
   {
      List<string> list = new List<string>();
      list.Add(ProjNrList.Element("ProjectNr").Value);

      ViewBag.ProjNrList = list;
      continue;
   }
   return View();
}





我的尝试:



我想我已经尝试了一切,但显然我没有。 ;-)

我尝试过multible循环,linq,readXML以及检索列表的许多不同方法。不知道下一步该尝试什么。 : - (



What I have tried:

I think I have tried everything, but obviously I have not. ;-)
I have tried multible loops, linq, readXML and many different ways of retrieving the list. Do not know what to try next. :-(

推荐答案

这就是问题所在,我知道为什么我也被它欺骗了,因为我试图让事情超出循环,但不完全是你做的方式。;-)

太棒了!谢谢!



That's what the problem was and I know why I got tricked by it too since I have tried to have things outside the loop, but not exactly the way you did it. ;-)
Great! Thanks!

<pre>List<string> list = new List<string>();
foreach (var ProjNrList in Activity)
{
   list.Add(ProjNrList.Element("ProjectNr").Value);
}
ViewBag.ProjNrList = list;
return View();


这篇关于如何在视图中显示所有特定的XML元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆