使用LINQ使用属性查询XML

时间:2013-01-31 17:46:01

标签: c# linq linq-to-xml

我在linq方面做得不是很好,所以如果代码=“111”&&和我正在尝试编写Linq查询来检查子主题节点是否存在isDisplay =“Y”或者没有。我在第二种方法中使用.Any条件,但我仍然不确定。

static void Main(string[] args)
{
    XElement rootElement = XElement.Load("TestXML.xml");
    int StyCode = 1;
    var lv1s = from lv1 in rootElement.Descendants("Class")
               where lv1.Attribute("Code").Value.Equals("001")
               select (from ltd in lv1.Descendants("Subject")
                       where ltd.Attribute("Course").Value.Equals("Engish")
                       select GetChildFromSubject(StyCode, ltd)).FirstOrDefault();

       }

private static bool GetChildFromSubject(int styCode, XElement subject)
{
    if (styCode == 0)
        return subject.Attribute("SpeciaGuest").Value.Equals("Y");
    else
    {
        //Below is the main issue with and condition on attributes.
        return subject.Attribute("AllTeachers").Value.Equals("Y") ||
               subject.Elements("Topic").Attributes("Code")
               .Any(x => x.Value.Equals("111")) &&       subject.Elements("Topic").Attributes("isDisplay")
                        .Any(y => y.Value.Equals("Y"));
    }
}

以下是XML文件

<Class Code="002">
    <Subject Course="Math" AllTeachers='Y' SpeciaGuest='N'>
      <Topic Code="1" isDisplay="Y">LAW1</Topic>
      <Topic Code="2" isDisplay="Y">
        LAW2
      </Topic>
      <Topic Code="3" isDisplay="N">
        LAW3
      </Topic>
    </Subject>
    <Subject Course="Engish" AllTeachers='N' SpeciaGuest='Y'>
      <Topic Code="111" isDisplay="Y">LAW1</Topic>
    </Subject>
    <Subject Course="History" AllTeachers='Y' SpeciaGuest='Y'></Subject>
  </Class>

1 个答案:

答案 0 :(得分:0)

根据你的评论:

  

Magnum:我想检查主题节点是否存在,如果code =“111”&amp;&amp; isDisplay = “Y”

如果您尝试返回TOPIC节点,如果代码= 111且isDiaply = Y,那么这是一次性LINQ查询:

List<XElement> subjects = template.Descendants("Subject")
            .Elements("Topic")
                .Where(elementNode => elementNode.Attribute("Code").Value == "111" && elementNode.Attribute("isDisplay").Value == "Y").ToList();