试图这样做但没有成功.P'se 帮我解决这个小问题

本文关键字:se 解决 问题 这样做 成功 | 更新日期: 2023-09-27 17:56:45

>伙计们来吧 我知道这对你们所有人来说似乎都是一次走过,但我未能实现我的意图。 我的 linq 查询

  XDocument doc = XDocument.Load(@"E:'OBJECT ORIENTED DEV'T'file.xml");
    XElement root = doc.Root;

    var items = from item in doc.Descendants("ModuleSchedule")
                                          .Descendants("ModuleTimeTable")
                where item.Attribute("Module_ID").Value.Equals("001")
                select new
                {

                   ModuleId = item.Attribute("Module_ID").Value, //works fine
                   Slots = item.Attribute("Day").Value  //Not sure how to achieve this
                   Slots = item.Attribute("Time").Value  // Not sure how to achieve   this
                };

    GridView1.DataSource = items;
    GridView1.DataBind();

这是我的 XML 结构

  <?xml version="1.0" encoding="utf-8"?>
<ModuleSchedule>
 <ModuleTimeTable Module_ID="001" ModuleName="Module Name 1">
  <Slot Day="Monday" Time="09:30"/>
  <Slot Day="Tuesday" Time="14:30"/>
  <Slot Day="Fridayday" Time="09:30"/>
  <Slot Day="Saturday" Time="12:30"/>
 </ModuleTimeTable>
<ModuleTimeTable Module_ID="002" ModuleName="Module Name 2">
  <Slot Day="Monday" Time="09:30"/>
  <Slot Day="Tuesday" Time="14:30"/>
  <Slot Day="Fridayday" Time="09:30"/>
  <Slot Day="Saturday" Time="12:30"/>
 </ModuleTimeTable>
<ModuleTimeTable Module_ID="003" ModuleName="Module Name 3">
  <Slot Day="Monday" Time="09:30"/>
  <Slot Day="Tuesday" Time="14:30"/>
  <Slot Day="Fridayday" Time="09:30"/>
  <Slot Day="Saturday" Time="12:30"/>    
</ModuleTimeTable>

我想检索与模块 ID 关联的所有插槽,将它们放在网格视图表中,例如日期和时间。

谢谢

试图这样做但没有成功.P'se 帮我解决这个小问题

而不是

 doc.Descendants("ModuleSchedule")
    .Descendants("ModuleTimeTable")

只需使用doc.Descendants("ModuleTimeTable")doc.Root.Elements("ModuleTimeTable")

此外,您可能希望在获取属性或元素的值时使用显式强制转换,以避免可能的异常:

var items = from item in doc.Descendants("ModuleTimeTable")
            where (string)item.Attribute("Module_ID") == "001"
            select new
            {
                ModuleId = (int) item.Attribute("Module_ID"),
                Day = (string) item.Element("Slot").Attribute("Day"),
                Time = (string) item.Element("Slot").Attribute("Time")
            };